WeightedSumFitter#

class causalpy.pymc_models.WeightedSumFitter[source]#

Used for synthetic control experiments.

Defines the PyMC model:

\[\begin{split}\sigma &\sim \mathrm{HalfNormal}(1) \\ \beta &\sim \mathrm{Dirichlet}(1,...,1) \\ \mu &= X \cdot \beta \\ y &\sim \mathrm{Normal}(\mu, \sigma) \\\end{split}\]

Example

>>> import causalpy as cp
>>> import numpy as np
>>> import xarray as xr
>>> from causalpy.pymc_models import WeightedSumFitter
>>> sc = cp.load_data("sc")
>>> control_units = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> X = xr.DataArray(
...     sc[control_units].values,
...     dims=["obs_ind", "coeffs"],
...     coords={"obs_ind": sc.index, "coeffs": control_units},
... )
>>> y = xr.DataArray(
...     sc['actual'].values.reshape((sc.shape[0], 1)),
...     dims=["obs_ind", "treated_units"],
...     coords={"obs_ind": sc.index, "treated_units": ["actual"]},
... )
>>> coords = {
...     "coeffs": control_units,
...     "treated_units": ["actual"],
...     "obs_ind": np.arange(sc.shape[0]),
... }
>>> wsf = WeightedSumFitter(sample_kwargs={"progressbar": False})
>>> wsf.fit(X, y, coords=coords)
Inference data...

Methods

WeightedSumFitter.__init__([sample_kwargs])

WeightedSumFitter.add_coord(name[, values, ...])

Register a dimension coordinate with the model.

WeightedSumFitter.add_coords(coords, *[, ...])

Vectorized version of Model.add_coord.

WeightedSumFitter.add_named_variable(var[, dims])

Add a random graph variable to the named variables of the model.

WeightedSumFitter.build_model(X, y, coords)

Defines the PyMC model

WeightedSumFitter.calculate_cumulative_impact(impact)

WeightedSumFitter.calculate_impact(y_true, ...)

WeightedSumFitter.check_start_vals(start, ...)

Check that the logp is defined and finite at the starting point.

WeightedSumFitter.compile_d2logp([vars, ...])

Compiled log probability density hessian function.

WeightedSumFitter.compile_dlogp([vars, jacobian])

Compiled log probability density gradient function.

WeightedSumFitter.compile_fn(outs, *[, ...])

Compiles a PyTensor function.

WeightedSumFitter.compile_logp([vars, ...])

Compiled log probability density function.

WeightedSumFitter.copy()

Clone the model.

WeightedSumFitter.create_value_var(rv_var, ...)

Create a TensorVariable that will be used as the random variable's "value" in log-likelihood graphs.

WeightedSumFitter.d2logp([vars, jacobian, ...])

Hessian of the models log-probability w.r.t.

WeightedSumFitter.debug([point, fn, verbose])

Debug model function at point.

WeightedSumFitter.dlogp([vars, jacobian])

Gradient of the models log-probability w.r.t.

WeightedSumFitter.eval_rv_shapes()

Evaluate shapes of untransformed AND transformed free variables.

WeightedSumFitter.fit(X, y[, coords])

Draw samples from posterior, prior predictive, and posterior predictive distributions, placing them in the model's idata attribute.

WeightedSumFitter.get_context([...])

WeightedSumFitter.initial_point([random_seed])

Compute the initial point of the model.

WeightedSumFitter.logp([vars, jacobian, sum])

Elemwise log-probability of the model.

WeightedSumFitter.logp_dlogp_function([...])

Compile a PyTensor function that computes logp and gradient.

WeightedSumFitter.make_obs_var(rv_var, data, ...)

Create a TensorVariable for an observed random variable.

WeightedSumFitter.name_for(name)

Check if name has prefix and adds if needed.

WeightedSumFitter.name_of(name)

Check if name has prefix and deletes if needed.

WeightedSumFitter.point_logps([point, ...])

Compute the log probability of point for all random variables in the model.

WeightedSumFitter.predict(X)

Predict data given input data X

WeightedSumFitter.print_coefficients(labels)

WeightedSumFitter.profile(outs, *[, n, ...])

Compile and profile a PyTensor function which returns outs and takes values of model vars as a dict as an argument.

WeightedSumFitter.register_data_var(data[, dims])

Register a data variable with the model.

WeightedSumFitter.register_rv(rv_var, name, *)

Register an (un)observed random variable with the model.

WeightedSumFitter.replace_rvs_by_values(...)

Clone and replace random variables in graphs with their value variables.

WeightedSumFitter.score(X, y)

Score the Bayesian \(R^2\) given inputs X and outputs y.

WeightedSumFitter.set_data(name, values[, ...])

Change the values of a data variable in the model.

WeightedSumFitter.set_dim(name, new_length)

Update a mutable dimension.

WeightedSumFitter.set_initval(rv_var, initval)

Set an initial value (strategy) for a random variable.

WeightedSumFitter.shape_from_dims(dims)

WeightedSumFitter.to_graphviz(*[, ...])

Produce a graphviz Digraph from a PyMC model.

Attributes

basic_RVs

List of random variables the model is defined in terms of.

continuous_value_vars

All the continuous value variables in the model.

coords

Coordinate values for model dimensions.

datalogp

PyTensor scalar of log-probability of the observed variables and potential terms.

dim_lengths

The symbolic lengths of dimensions in the model.

discrete_value_vars

All the discrete value variables in the model.

isroot

observedlogp

PyTensor scalar of log-probability of the observed variables.

parent

potentiallogp

PyTensor scalar of log-probability of the Potential terms.

prefix

root

unobserved_RVs

List of all random variables, including deterministic ones.

unobserved_value_vars

List of all random variables (including untransformed projections), as well as deterministics used as inputs and outputs of the model's log-likelihood graph.

value_vars

List of unobserved random variables used as inputs to the model's log-likelihood (which excludes deterministics).

varlogp

PyTensor scalar of log-probability of the unobserved random variables (excluding deterministic).

varlogp_nojac

PyTensor scalar of log-probability of the unobserved random variables (excluding deterministic) without jacobian term.

__init__(sample_kwargs=None)#
Parameters:

sample_kwargs (Optional[Dict[str, Any]]) – A dictionary of kwargs that get unpacked and passed to the pymc.sample() function. Defaults to an empty dictionary.

classmethod __new__(*args, **kwargs)#