tfcausalimpact

repository·master·Indexed 20 days ago

https://github.com/willianfuks/tfcausalimpact

A Python implementation of Google's Causal Impact algorithm built on TensorFlow Probability. It uses Bayesian structural time series models to perform causal inference by comparing observed data against counter-factual predictions. The library supports Variational Inference (VI) and Hamiltonian Monte Carlo (HMC) fitting methods, and allows for the use of custom tfp.sts.StructuralTimeSeries models.

Tokens
2.1K
Snippets
8
Records
10
Agent score
22%

What's inside tfcausalimpact

  1. How Causal Impact works

    master

    The algorithm fits a Bayesian structural time series model on past observed data to predict what future data would look like (the counter-factual). It then compares this prediction against the actual observed data to extract statistical conclusions about an intervention.

    To run the model, you need:

    • y: The observed data.
    • X: Covariates used for linear regression.
    • pre-period: An interval selecting data before the intervention.
    • post-period: An interval selecting data after the intervention.
  2. Use CausalImpact for causal analysis

    master

    To perform a causal impact analysis, import CausalImpact from causalimpact. Pass your data (as a pandas DataFrame), the pre_period indices/dates, and the post_period indices/dates to the constructor.

    You can then generate a summary of the results or a detailed report, and visualize the impact using .plot().

    import pandas as pd
    from causalimpact import CausalImpact
    
    # Load data containing 'y' and covariates 'X'
    data = pd.read_csv('your_data.csv')[['y', 'X']]
    
    # Define periods (can be integer indices or date strings)
    pre_period = [0, 69]
    post_period = [70, 99]
    
    # Initialize and run the model
    ci = CausalImpact(data, pre_period, post_period)
    
    # View results
    print(ci.summary())           # Standard summary
    print(ci.summary(output='report')) # Detailed report
    ci.plot()                     # Visual plot
  3. Configure the fit method via model_args

    master

    By default, tfcausalimpact uses Variational Inference, which is faster and suitable for most use cases.

    If high precision is required, you can switch to the Hamiltonian Monte Carlo (HMC) algorithm by passing model_args={'fit_method': 'hmc'} to the CausalImpact constructor. Note that HMC is significantly slower and may take an hour or more for complex time series with many data points.

    ci = CausalImpact(data, pre_period, post_period, model_args={'fit_method': 'hmc'})
  4. Configure CausalImpact via model_args

    master

    The model_args dictionary allows you to control the behavior of the state space model and the Bayesian fitting process.

    Available keys:

    • standardize (bool): If True, standardizes data to zero mean and unitary standard deviation.
    • prior_level_sd (float, optional): Prior value for the local level standard deviation. Use None for automatic optimization. Low values (e.g., 0.01) are good if covariates explain the response well; higher values (e.g., 0.1) are better if they don't.
    • fit_method (str): Either 'vi' (default) or 'hmc'.
    • nseasons (int): Specifies the duration of the seasonal component (e.g., 7 for weekly seasonality in daily data).
    • season_duration (int): Number of data points each value in a season spans. If > 1, nseasons must also be > 1.
    model_args = {
        'nseasons': 7,
        'season_duration': 24,
        'fit_method': 'hmc',
        'standardize': True
    }
    ci = CausalImpact(data, pre_period, post_period, model_args=model_args)
  5. Use a custom TensorFlow Probability model

    master

    Instead of the default tfp.sts.LocalLevel model, you can pass a custom tfp.sts.StructuralTimeSeries object to the model argument.

    Important Note on Standardization: If you provide a custom model, tfcausalimpact makes no assumptions about the input data. If you set model_args={'standardize': True}, the library will standardize the data internally, which might break the relationship to the model you built manually. It is recommended to perform all data processing (like standardization) manually before building the model and calling CausalImpact.

    import tensorflow_probability as tfp
    
    # 1. Prepare and standardize data manually
    from causalimpact.misc import standardize
    data_normed = standardize(data)[0]
    
    # 2. Build custom model using the normed data
    obs_series = data_normed.loc[:pre_period[1], 0]
    local_linear = tfp.sts.LocalLinearTrend(observed_time_series=obs_series)
    seasonal = tfp.sts.Seasonal(num_seasons=7, observed_time_series=obs_series)
    model = tfp.sts.Sum([local_linear, seasonal], observed_time_series=obs_series)
    
    # 3. Pass to CausalImpact
    ci = CausalImpact(data_normed, pre_period, post_period, model=model, model_args={'standardize': False})
  6. Visualize results with plot()

    master

    The plot() method generates graphics representing the Causal Impact results.

    Arguments:

    • panels (List[str]): Which graphics to include. Options are:
      • 'original': Original data, forecast means, and credible intervals.
      • 'pointwise': Point-wise differences between observed data and predictions.
      • 'cumulative': Cumulative summation of the differences.
    • figsize (Tuple[int]): Width and height of the figure.
    • show (bool): If True, calls plt.show(). If False, allows you to manipulate the figure/axis manually (e.g., plt.gca() or plt.gcf()).
    ci.plot(panels=['original', 'cumulative'], figsize=(12, 8), show=False)
    # You can then use matplotlib to save or modify
    import matplotlib.pyplot as plt
    plt.savefig('impact_plot.png')
  7. Generate summary reports with summary()

    master

    The summary() method produces a text report of the causal impact analysis.

    Arguments:

    • output (str):
      • 'summary': A simple output showing general metrics like expected absolute or relative effect.
      • 'report': A more detailed report.
    • digits (int): Number of decimal places to round to (default is 2).

    Returns a string containing the results.

    print(ci.summary(output='report', digits=3))
  8. Use the CausalImpact class for Bayesian structural time series analysis

    master

    The CausalImpact class implements the Causal Impact algorithm to perform Bayesian structural time series analysis. It fits a structural state space model to observed data y and uses Bayesian inferencing to find the posterior distribution of model parameters (like level, trend, and season).

    It supports two fitting methods via model_args:

    • 'vi' (Variational Inference): Faster but less accurate (default).
    • 'hmc' (Hamiltonian Monte Carlo): More accurate but significantly slower.

    To use it, provide your data (as a numpy.array or pd.DataFrame), a pre_period (the period before the intervention), and a post_period (the period after the intervention).

    import numpy as np
    import pandas as pd
    from causalimpact import CausalImpact
    
    # Example with numpy array
    data = np.random.rand(100, 2)
    pre_period = [0, 69]
    post_period = [70, 99]
    
    ci = CausalImpact(data, pre_period, post_period)
    print(ci.summary())
    ci.plot()