HSGP#

class pymc_marketing.mmm.hsgp.HSGP(**data)[source]#

HSGP component.

Examples

Literature recommended HSGP configuration:

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGP

seed = sum(map(ord, "Out of the box GP"))
rng = np.random.default_rng(seed)

n = 52
X = np.arange(n)

hsgp = HSGP.parameterize_from_data(
    X=X,
    dims="time",
)

dates = pd.date_range("2022-01-01", periods=n, freq="W-MON")
coords = {
    "time": dates,
}
prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
hsgp.plot_curve(curve, sample_kwargs={"rng": rng})
plt.show()

(Source code, png, hires.png, pdf)

../../_images/pymc_marketing-mmm-hsgp-HSGP-1.png

HSGP with different covariance function

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGP

seed = sum(map(ord, "Change of covariance function"))
rng = np.random.default_rng(seed)

n = 52
X = np.arange(n)

hsgp = HSGP.parameterize_from_data(
    X=X,
    cov_func="matern32",
    dims="time",
)

dates = pd.date_range("2022-01-01", periods=n, freq="W-MON")
coords = {
    "time": dates,
}
prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
hsgp.plot_curve(curve, sample_kwargs={"rng": rng})
plt.show()

(Source code, png, hires.png, pdf)

../../_images/pymc_marketing-mmm-hsgp-HSGP-2.png

New data predictions with HSGP

import numpy as np
import pandas as pd

import pymc as pm

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGP
from pymc_marketing.prior import Prior

seed = sum(map(ord, "New data predictions"))
rng = np.random.default_rng(seed)

eta = Prior("Exponential", lam=1)
ls = Prior("InverseGamma", alpha=2, beta=1)
hsgp = HSGP(
    eta=eta,
    ls=ls,
    m=20,
    L=150,
    dims=("time", "channel"),
)

n = 52
X = np.arange(n)

dates = pd.date_range("2022-01-01", periods=n, freq="W-MON")
coords = {"time": dates, "channel": ["A", "B"]}
with pm.Model(coords=coords) as model:
    data = pm.Data("data", X, dims="time")
    hsgp.register_data(data).create_variable("f")
    idata = pm.sample_prior_predictive(random_seed=rng)

prior = idata.prior

n_new = 10
X_new = np.arange(n, n + n_new)
new_dates = pd.date_range("2023-01-01", periods=n_new, freq="W-MON")

with model:
    pm.set_data(
        new_data={
            "data": X_new,
        },
        coords={"time": new_dates},
    )
    post = pm.sample_posterior_predictive(
        prior,
        var_names=["f"],
        random_seed=rng,
    )

chain, draw = 0, 50
colors = ["C0", "C1"]

def get_sample(curve):
    return curve.loc[chain, draw].to_series().unstack()

ax = prior["f"].pipe(get_sample).plot(color=colors)
post.posterior_predictive["f"].pipe(get_sample).plot(
    ax=ax, color=colors, linestyle="--", legend=False
)
ax.set(xlabel="time", ylabel="f", title="New data predictions")
plt.show()

(Source code, png, hires.png, pdf)

../../_images/pymc_marketing-mmm-hsgp-HSGP-3.png

Higher dimensional HSGP

import numpy as np
import pymc as pm

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGP

seed = sum(map(ord, "Higher dimensional HSGP"))
rng = np.random.default_rng(seed)

n = 52
X = np.arange(n)

hsgp = HSGP.parameterize_from_data(
    X=X,
    dims=("time", "channel", "product"),
)

coords = {
    "time": range(n),
    "channel": ["A", "B"],
    "product": ["X", "Y", "Z"],
}
prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
fig, _ = hsgp.plot_curve(
    curve,
    sample_kwargs={"rng": rng},
    subplot_kwargs={"figsize": (12, 8), "ncols": 3},
)
fig.suptitle("Higher dimensional HSGP prior")
plt.show()

(Source code, png, hires.png, pdf)

../../_images/pymc_marketing-mmm-hsgp-HSGP-4.png

Methods

HSGP.__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

HSGP.construct([_fields_set])

HSGP.copy(*[, include, exclude, update, deep])

Returns a copy of the model.

HSGP.create_variable(name)

Create a variable from HSGP configuration.

HSGP.deterministics_to_replace(name)

Name of the Deterministic variables that are replaced with pm.Flat for out-of-sample.

HSGP.dict(*[, include, exclude, by_alias, ...])

HSGP.from_dict(data)

Create an object from a dictionary.

HSGP.from_orm(obj)

HSGP.json(*[, include, exclude, by_alias, ...])

HSGP.model_construct([_fields_set])

Creates a new instance of the Model class with validated data.

HSGP.model_copy(*[, update, deep])

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#model_copy

HSGP.model_dump(*[, mode, include, exclude, ...])

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

HSGP.model_dump_json(*[, indent, include, ...])

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json

HSGP.model_json_schema([by_alias, ...])

Generates a JSON schema for a model class.

HSGP.model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

HSGP.model_post_init(_BaseModel__context)

Override this method to perform additional initialization after __init__ and model_construct.

HSGP.model_rebuild(*[, force, raise_errors, ...])

Try to rebuild the pydantic-core schema for the model.

HSGP.model_validate(obj, *[, strict, ...])

Validate a pydantic model instance.

HSGP.model_validate_json(json_data, *[, ...])

Usage docs: https://docs.pydantic.dev/2.10/concepts/json/#json-parsing

HSGP.model_validate_strings(obj, *[, ...])

Validate the given object with string data against the Pydantic model.

HSGP.parameterize_from_data(X, dims[, ...])

Create a HSGP informed by the data with literature-based recommendations.

HSGP.parse_file(path, *[, content_type, ...])

HSGP.parse_obj(obj)

HSGP.parse_raw(b, *[, content_type, ...])

HSGP.plot_curve(curve[, subplot_kwargs, ...])

Plot the curve.

HSGP.register_data(X)

Register the data to be used in the model.

HSGP.sample_prior([coords])

Sample from the prior distribution.

HSGP.schema([by_alias, ref_template])

HSGP.schema_json(*[, by_alias, ref_template])

HSGP.to_dict()

Convert the object to a dictionary.

HSGP.update_forward_refs(**localns)

HSGP.validate(value)

Attributes

model_computed_fields

model_config

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_extra

Get extra fields set during validation.

model_fields

model_fields_set

Returns the set of fields that have been explicitly set on this model instance.

ls

eta

L

centered

drop_first

cov_func

m

X

X_mid

dims