EfectoTendenciaLineal#

class pymc_marketing.mmm.additive_effect.LinearTrendEffect(**data)[fuente]#

Envoltorio para LinearTrend para usar con el protocolo MuEffect de MMM.

Esta clase adapta el componente LinearTrend para ser utilizado como un efecto aditivo en el modelo MMM.

Parámetros:
tendencia : LinearTrendTendenciaLineal

La instancia LinearTrend a envolver.

prefijo : strstr

El prefijo a utilizar para las variables en el modelo.

date_dim_namestr

The name of the date dimension in the model.

Ejemplos

Predicciones fuera de muestra:

Nota

No se utilizan nuevos puntos de cambio para las predicciones fuera de la muestra. El efecto de tendencia se extrapola linealmente a partir del último punto de cambio.

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

import pymc as pm

from pymc_marketing.mmm.linear_trend import LinearTrend
from pymc_marketing.mmm.additive_effect import LinearTrendEffect

seed = sum(map(ord, "LinearTrend out of sample"))
rng = np.random.default_rng(seed)

class MockMMM:
    pass

dates = pd.date_range("2025-01-01", periods=52, freq="W")
coords = {"date": dates}
model = pm.Model(coords=coords)

mock_mmm = MockMMM()
mock_mmm.dims = ()
mock_mmm.model = model

effect = LinearTrendEffect(
    trend=LinearTrend(n_changepoints=8),
    prefix="trend",
)

with mock_mmm.model:
    effect.create_data(mock_mmm)
    pmd.Deterministic(
        "effect",
        effect.create_effect(mock_mmm),
        dims="date",
    )

    idata = pm.sample_prior_predictive(random_seed=rng)

idata["posterior"] = idata.prior

n_new = 10 + 1
new_dates = pd.date_range(
    dates.max(),
    periods=n_new,
    freq="W",
)

with mock_mmm.model:
    mock_mmm.model.set_dim("date", n_new, new_dates)

    effect.set_data(mock_mmm, mock_mmm.model, None)

    pm.sample_posterior_predictive(
        idata,
        var_names=["effect"],
        random_seed=rng,
        extend_inferencedata=True,
    )

draw = rng.choice(range(idata.posterior.sizes["draw"]))
sel = dict(chain=0, draw=draw)

before = idata.posterior.effect.sel(sel).to_series()
after = idata.posterior_predictive.effect.sel(sel).to_series()

ax = before.plot(color="C0")
after.plot(color="C0", linestyle="dashed", ax=ax)
plt.show()

(Source code)

Métodos

LinearTrendEffect.__init__(**data)

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

LinearTrendEffect.construct([_fields_set])

LinearTrendEffect.copy(*[, include, ...])

Returns a copy of the model.

LinearTrendEffect.create_data(mmm)

Cree los datos requeridos en el modelo.

LinearTrendEffect.create_effect(mmm)

Cree el efecto de tendencia en el modelo.

LinearTrendEffect.dict(*[, include, ...])

LinearTrendEffect.from_dict(data)

Reconstruct from a dict, using registry for nested LinearTrend.

LinearTrendEffect.from_orm(obj)

LinearTrendEffect.json(*[, include, ...])

LinearTrendEffect.model_construct([_fields_set])

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

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

!!! abstract "Usage Documentation"

LinearTrendEffect.model_dump(*[, mode, ...])

!!! abstract "Usage Documentation"

LinearTrendEffect.model_dump_json(*[, ...])

!!! abstract "Usage Documentation"

LinearTrendEffect.model_json_schema([...])

Generates a JSON schema for a model class.

LinearTrendEffect.model_parametrized_name(params)

Compute the class name for parametrizations of generic classes.

LinearTrendEffect.model_post_init(context, /)

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

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

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

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

Validate a pydantic model instance.

LinearTrendEffect.model_validate_json(...[, ...])

!!! abstract "Usage Documentation"

LinearTrendEffect.model_validate_strings(obj, *)

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

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

LinearTrendEffect.parse_obj(obj)

LinearTrendEffect.parse_raw(b, *[, ...])

LinearTrendEffect.schema([by_alias, ...])

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

LinearTrendEffect.set_data(mmm, modelo, X)

Establezca los datos para nuevas predicciones.

LinearTrendEffect.to_dict([_orig])

Serialize to a dict via Pydantic model_dump.

LinearTrendEffect.update_forward_refs(**localns)

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

trend

prefix

date_dim_name

linear_trend_first_date