HSGPPeriodic#

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

HSGP component for periodic data.

Examples

HSGPPeriodic with default configuration:

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGPPeriodic
from pymc_extras.prior import Prior

seed = sum(map(ord, "Periodic GP"))
rng = np.random.default_rng(seed)

n = 52 * 3
dates = pd.date_range("2023-01-01", periods=n, freq="W-MON")
X = np.arange(n)
coords = {
    "time": dates,
}
scale = Prior("HalfNormal", sigma=1)
ls = Prior("InverseGamma", alpha=2, beta=1)

hsgp = HSGPPeriodic(
    scale=scale,
    m=20,
    cov_func="periodic",
    ls=ls,
    period=52,
    dims="time",
)
hsgp.register_data(X)

prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
fig, axes = hsgp.plot_curve(
    curve,
    n_samples=3,
    random_seed=rng,
)
ax = axes[0]
ax.set(xlabel="Date", ylabel="f", title="HSGP with period of 52 weeks")
plt.show()

(Source code)

HSGPPeriodic with link function via transform argument

Note

The transform parameter must be registered or from either pytensor.tensor or pymc.math namespaces. See the pymc_extras.prior.register_tensor_transform()

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGPPeriodic
from pymc_extras.prior import Prior

seed = sum(map(ord, "Periodic GP"))
rng = np.random.default_rng(seed)

n = 52 * 3
dates = pd.date_range("2023-01-01", periods=n, freq="W-MON")
X = np.arange(n)
coords = {
    "time": dates,
}
scale = Prior("Gamma", mu=0.25, sigma=0.1)
ls = Prior("InverseGamma", alpha=2, beta=1)

hsgp = HSGPPeriodic(
    scale=scale,
    m=20,
    cov_func="periodic",
    ls=ls,
    period=52,
    dims="time",
    transform="exp",
)
hsgp.register_data(X)

prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
fig, axes = hsgp.plot_curve(
    curve,
    n_samples=3,
    random_seed=rng,
)
ax = axes[0]
ax.set(xlabel="Date", ylabel="f", title="HSGP with period of 52 weeks")
plt.show()

(Source code)

Demeaned basis for HSGPPeriodic

import numpy as np
import pandas as pd
import xarray as xr

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGPPeriodic
from pymc_marketing.plot import plot_curve

seed = sum(map(ord, "Periodic GP"))
rng = np.random.default_rng(seed)

scale = 0.25
ls = 1
kwargs = dict(ls=ls, scale=scale, period=52, cov_func="periodic", dims="time", m=20)

n = 52 * 3
dates = pd.date_range("2023-01-01", periods=n, freq="W-MON")
X = np.arange(n)
coords = {"time": dates}

hsgp = HSGPPeriodic(demeaned_basis=False, **kwargs).register_data(X)
hsgp_demeaned = HSGPPeriodic(demeaned_basis=True, **kwargs).register_data(X)

def sample_curve(hsgp):
    return hsgp.sample_prior(coords=coords, random_seed=rng)["f"]

non_demeaned = sample_curve(hsgp).rename("False")
demeaned = sample_curve(hsgp_demeaned).rename("True")

combined = xr.merge([non_demeaned, demeaned]).to_array("demeaned")
_, axes = combined.pipe(plot_curve, "time", same_axes=True)
axes[0].set(title="Demeaned the intercepty first basis")
plt.show()

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

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

Higher dimensional HSGPPeriodic with periodic data

import numpy as np
import pandas as pd

import pymc as pm

import matplotlib.pyplot as plt

from pymc_marketing.mmm import HSGPPeriodic
from pymc_extras.prior import Prior

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

n = 52 * 3
dates = pd.date_range("2023-01-01", periods=n, freq="W-MON")
X = np.arange(n)

scale = Prior("HalfNormal", sigma=1)
ls = Prior("InverseGamma", alpha=2, beta=1)

hsgp = HSGPPeriodic(
    X=X,
    scale=scale,
    ls=ls,
    m=20,
    cov_func="periodic",
    period=52,
    dims=("time", "channel", "product"),
)

coords = {
    "time": dates,
    "channel": ["A", "B"],
    "product": ["X", "Y", "Z"],
}
prior = hsgp.sample_prior(coords=coords, random_seed=rng)
curve = prior["f"]
fig, axes = hsgp.plot_curve(
    curve,
    n_samples=3,
    random_seed=rng,
    subplot_kwargs={"figsize": (12, 8), "ncols": 3},
)
plt.show()

(Source code)

Methods

HSGPPeriodic.__init__(**data)

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

HSGPPeriodic.construct([_fields_set])

HSGPPeriodic.copy(*[, include, exclude, ...])

Returns a copy of the model.

HSGPPeriodic.create_variable(name)

Create HSGP variable.

HSGPPeriodic.deterministics_to_replace(name)

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

HSGPPeriodic.dict(*[, include, exclude, ...])

HSGPPeriodic.from_dict(data)

Create an object from a dictionary.

HSGPPeriodic.from_orm(obj)

HSGPPeriodic.json(*[, include, exclude, ...])

HSGPPeriodic.model_construct([_fields_set])

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

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

!!! abstract "Usage Documentation"

HSGPPeriodic.model_dump(*[, mode, include, ...])

!!! abstract "Usage Documentation"

HSGPPeriodic.model_dump_json(*[, indent, ...])

!!! abstract "Usage Documentation"

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

Generates a JSON schema for a model class.

HSGPPeriodic.model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

HSGPPeriodic.model_post_init(context, /)

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

HSGPPeriodic.model_rebuild(*[, force, ...])

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

HSGPPeriodic.model_validate(obj, *[, ...])

Validate a pydantic model instance.

HSGPPeriodic.model_validate_json(json_data, *)

!!! abstract "Usage Documentation"

HSGPPeriodic.model_validate_strings(obj, *)

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

HSGPPeriodic.parse_file(path, *[, ...])

HSGPPeriodic.parse_obj(obj)

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

HSGPPeriodic.plot_curve(curve[, n_samples, ...])

Plot the curve.

HSGPPeriodic.register_data(X)

Register the data to be used in the model.

HSGPPeriodic.sample_prior([coords])

Sample from the prior distribution.

HSGPPeriodic.schema([by_alias, ref_template])

HSGPPeriodic.schema_json(*[, by_alias, ...])

HSGPPeriodic.to_dict()

Convert the object to a dictionary.

HSGPPeriodic.update_forward_refs(**localns)

HSGPPeriodic.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

scale

cov_func

period

m

X

X_mid

dims

transform

demeaned_basis