synthe 0.9.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- synthe/__init__.py +28 -0
- synthe/adaptivehistsampler.py +180 -0
- synthe/bayesiantweediesalesgenerator.py +466 -0
- synthe/conformal_inference.py +536 -0
- synthe/distro_simulator.py +1219 -0
- synthe/diversity_generator.py +196 -0
- synthe/empirical_copula.py +824 -0
- synthe/healthsims.py +283 -0
- synthe/helpers.py +342 -0
- synthe/meboot.py +500 -0
- synthe/metrics.py +179 -0
- synthe/row_subsampling.py +71 -0
- synthe/stratified_sampling.py +195 -0
- synthe/ts_distro_simulator.py +908 -0
- synthe/utils.py +364 -0
- synthe-0.9.1.dist-info/METADATA +103 -0
- synthe-0.9.1.dist-info/RECORD +21 -0
- synthe-0.9.1.dist-info/WHEEL +5 -0
- synthe-0.9.1.dist-info/entry_points.txt +2 -0
- synthe-0.9.1.dist-info/licenses/LICENSE +32 -0
- synthe-0.9.1.dist-info/top_level.txt +1 -0
synthe/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Top-level package for synthe."""
|
|
2
|
+
|
|
3
|
+
__author__ = """T. Moudiki"""
|
|
4
|
+
__email__ = "thierry.moudiki@gmail.com"
|
|
5
|
+
|
|
6
|
+
from .adaptivehistsampler import AdaptiveHistogramSampler # noqa: F401
|
|
7
|
+
from .distro_simulator import DistroSimulator # noqa: F401
|
|
8
|
+
from .empirical_copula import EmpiricalCopula # noqa: F401
|
|
9
|
+
from .stratified_sampling import StratifiedClusteringSubsampling
|
|
10
|
+
from .row_subsampling import SubSampler
|
|
11
|
+
from .healthsims import SmartHealthSimulator # noqa: F401
|
|
12
|
+
from .metrics import DistanceMetrics # noqa: F401
|
|
13
|
+
from .meboot import MaximumEntropyBootstrap
|
|
14
|
+
from .ts_distro_simulator import TsDistroSimulator # noqa: F401
|
|
15
|
+
from .diversity_generator import DiversityGenerator # noqa: F401
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"AdaptiveHistogramSampler",
|
|
19
|
+
"DistroSimulator",
|
|
20
|
+
"EmpiricalCopula",
|
|
21
|
+
"StratifiedClusteringSubsampling",
|
|
22
|
+
"SubSampler",
|
|
23
|
+
"SmartHealthSimulator",
|
|
24
|
+
"DistanceMetrics",
|
|
25
|
+
"MaximumEntropyBootstrap",
|
|
26
|
+
"TsDistroSimulator",
|
|
27
|
+
"DiversityGenerator",
|
|
28
|
+
]
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
from scipy import stats
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AdaptiveHistogramSampler:
|
|
7
|
+
def __init__(self, n_bins=10, method="quantile", seed=123):
|
|
8
|
+
self.n_bins = n_bins
|
|
9
|
+
self.method = method
|
|
10
|
+
self.rng = np.random.default_rng(seed)
|
|
11
|
+
self.bin_edges = None
|
|
12
|
+
self.bin_indices = None
|
|
13
|
+
self.unique_bins = None
|
|
14
|
+
self.bin_probs = None
|
|
15
|
+
self.X = None
|
|
16
|
+
self.n = None
|
|
17
|
+
self.d = None
|
|
18
|
+
|
|
19
|
+
def fit(self, X):
|
|
20
|
+
self.X = np.asarray(X)
|
|
21
|
+
self.n, self.d = self.X.shape
|
|
22
|
+
|
|
23
|
+
self.bin_edges = []
|
|
24
|
+
for j in range(self.d):
|
|
25
|
+
xj = self.X[:, j]
|
|
26
|
+
if self.method == "quantile":
|
|
27
|
+
edges_j = np.quantile(xj, np.linspace(0, 1, self.n_bins + 1))
|
|
28
|
+
else:
|
|
29
|
+
edges_j = np.linspace(xj.min(), xj.max(), self.n_bins + 1)
|
|
30
|
+
self.bin_edges.append(edges_j)
|
|
31
|
+
|
|
32
|
+
# Assign points to bins
|
|
33
|
+
bin_idx = np.zeros((self.n, self.d), dtype=int)
|
|
34
|
+
for j in range(self.d):
|
|
35
|
+
bin_idx[:, j] = np.digitize(self.X[:, j], self.bin_edges[j]) - 1
|
|
36
|
+
bin_idx[:, j] = np.clip(bin_idx[:, j], 0, self.n_bins - 1)
|
|
37
|
+
self.bin_indices = bin_idx
|
|
38
|
+
|
|
39
|
+
bin_ids = np.ravel_multi_index(
|
|
40
|
+
self.bin_indices.T, (self.n_bins,) * self.d
|
|
41
|
+
)
|
|
42
|
+
unique_bins, counts = np.unique(bin_ids, return_counts=True)
|
|
43
|
+
self.unique_bins = unique_bins
|
|
44
|
+
self.bin_probs = counts / counts.sum()
|
|
45
|
+
|
|
46
|
+
def sample(
|
|
47
|
+
self,
|
|
48
|
+
n_samples,
|
|
49
|
+
oversample=False,
|
|
50
|
+
oversample_method="bootstrap",
|
|
51
|
+
jitter_scale=0.05,
|
|
52
|
+
):
|
|
53
|
+
if self.bin_probs is None:
|
|
54
|
+
raise RuntimeError("You must call `fit` before `sample`.")
|
|
55
|
+
|
|
56
|
+
chosen_bins = self.rng.choice(
|
|
57
|
+
self.unique_bins, size=n_samples, p=self.bin_probs
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
if not oversample:
|
|
61
|
+
return self._subsample_existing(chosen_bins)
|
|
62
|
+
|
|
63
|
+
if oversample_method == "uniform":
|
|
64
|
+
return self._oversample_uniform(chosen_bins)
|
|
65
|
+
elif oversample_method == "bootstrap":
|
|
66
|
+
return self._oversample_bootstrap(chosen_bins)
|
|
67
|
+
elif oversample_method == "jitter":
|
|
68
|
+
return self._oversample_jitter(chosen_bins, jitter_scale)
|
|
69
|
+
else:
|
|
70
|
+
raise ValueError(f"Unknown oversample_method: {oversample_method}")
|
|
71
|
+
|
|
72
|
+
# --- Internal helpers ------------------------------------------------
|
|
73
|
+
def _subsample_existing(self, chosen_bins):
|
|
74
|
+
bin_ids = np.ravel_multi_index(
|
|
75
|
+
self.bin_indices.T, (self.n_bins,) * self.d
|
|
76
|
+
)
|
|
77
|
+
X_sampled = []
|
|
78
|
+
for b in chosen_bins:
|
|
79
|
+
idx_in_bin = np.where(bin_ids == b)[0]
|
|
80
|
+
i = self.rng.choice(idx_in_bin)
|
|
81
|
+
X_sampled.append(self.X[i])
|
|
82
|
+
return np.array(X_sampled)
|
|
83
|
+
|
|
84
|
+
def _oversample_uniform(self, chosen_bins):
|
|
85
|
+
X_sampled = []
|
|
86
|
+
for b in chosen_bins:
|
|
87
|
+
multi_idx = np.unravel_index(b, (self.n_bins,) * self.d)
|
|
88
|
+
coords = []
|
|
89
|
+
for j, bi in enumerate(multi_idx):
|
|
90
|
+
left = self.bin_edges[j][bi]
|
|
91
|
+
right = self.bin_edges[j][bi + 1]
|
|
92
|
+
coords.append(self.rng.uniform(left, right))
|
|
93
|
+
X_sampled.append(coords)
|
|
94
|
+
return np.array(X_sampled)
|
|
95
|
+
|
|
96
|
+
def _oversample_bootstrap(self, chosen_bins):
|
|
97
|
+
return self._subsample_existing(chosen_bins)
|
|
98
|
+
|
|
99
|
+
def _oversample_jitter(self, chosen_bins, jitter_scale):
|
|
100
|
+
base_points = self._subsample_existing(chosen_bins)
|
|
101
|
+
noise = self.rng.normal(scale=jitter_scale, size=base_points.shape)
|
|
102
|
+
return base_points + noise
|
|
103
|
+
|
|
104
|
+
# --- Visualization ----------------------------------------------------
|
|
105
|
+
def plot_comparison(self, X_sampled, bins=30):
|
|
106
|
+
"""Plot joint 2D histogram and marginal distributions (for d=2)."""
|
|
107
|
+
if self.d != 2:
|
|
108
|
+
raise ValueError("plot_comparison only supports 2D currently.")
|
|
109
|
+
|
|
110
|
+
fig = plt.figure(figsize=(10, 10))
|
|
111
|
+
grid = plt.GridSpec(4, 4, hspace=0.3, wspace=0.3)
|
|
112
|
+
|
|
113
|
+
main_ax = fig.add_subplot(grid[1:, :-1])
|
|
114
|
+
y_hist = fig.add_subplot(grid[0, :-1], sharex=main_ax)
|
|
115
|
+
x_hist = fig.add_subplot(grid[1:, -1], sharey=main_ax)
|
|
116
|
+
|
|
117
|
+
# 2D histogram
|
|
118
|
+
main_ax.hist2d(
|
|
119
|
+
self.X[:, 0], self.X[:, 1], bins=bins, alpha=0.5, cmap="Blues"
|
|
120
|
+
)
|
|
121
|
+
main_ax.hist2d(
|
|
122
|
+
X_sampled[:, 0], X_sampled[:, 1], bins=bins, alpha=0.5, cmap="Reds"
|
|
123
|
+
)
|
|
124
|
+
main_ax.set_xlabel("X1")
|
|
125
|
+
main_ax.set_ylabel("X2")
|
|
126
|
+
main_ax.set_title("Joint distribution")
|
|
127
|
+
|
|
128
|
+
# Marginals
|
|
129
|
+
y_hist.hist(
|
|
130
|
+
self.X[:, 0], bins=bins, color="blue", alpha=0.5, density=True
|
|
131
|
+
)
|
|
132
|
+
y_hist.hist(
|
|
133
|
+
X_sampled[:, 0], bins=bins, color="red", alpha=0.5, density=True
|
|
134
|
+
)
|
|
135
|
+
x_hist.hist(
|
|
136
|
+
self.X[:, 1],
|
|
137
|
+
bins=bins,
|
|
138
|
+
orientation="horizontal",
|
|
139
|
+
color="blue",
|
|
140
|
+
alpha=0.5,
|
|
141
|
+
density=True,
|
|
142
|
+
)
|
|
143
|
+
x_hist.hist(
|
|
144
|
+
X_sampled[:, 1],
|
|
145
|
+
bins=bins,
|
|
146
|
+
orientation="horizontal",
|
|
147
|
+
color="red",
|
|
148
|
+
alpha=0.5,
|
|
149
|
+
density=True,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
y_hist.axis("off")
|
|
153
|
+
x_hist.axis("off")
|
|
154
|
+
|
|
155
|
+
plt.show()
|
|
156
|
+
|
|
157
|
+
# --- Goodness of fit tests -------------------------------------------
|
|
158
|
+
def goodness_of_fit(self, X_sampled):
|
|
159
|
+
"""
|
|
160
|
+
Compare marginals with Kolmogorov–Smirnov and Anderson–Darling tests.
|
|
161
|
+
Returns dict of test results for each dimension.
|
|
162
|
+
"""
|
|
163
|
+
results = {}
|
|
164
|
+
for j in range(self.d):
|
|
165
|
+
x_orig = self.X[:, j]
|
|
166
|
+
x_samp = X_sampled[:, j]
|
|
167
|
+
|
|
168
|
+
# KS test
|
|
169
|
+
ks_stat, ks_p = stats.ks_2samp(x_orig, x_samp)
|
|
170
|
+
|
|
171
|
+
# Anderson-Darling test
|
|
172
|
+
ad_result = stats.anderson_ksamp([x_orig, x_samp])
|
|
173
|
+
|
|
174
|
+
results[f"dim_{j}"] = {
|
|
175
|
+
"ks_statistic": ks_stat,
|
|
176
|
+
"ks_pvalue": ks_p,
|
|
177
|
+
"ad_statistic": ad_result.statistic,
|
|
178
|
+
"ad_significance_level": ad_result.significance_level,
|
|
179
|
+
}
|
|
180
|
+
return results
|
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.linear_model import TweedieRegressor
|
|
4
|
+
from sklearn.preprocessing import StandardScaler
|
|
5
|
+
from scipy import stats
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BayesianTweedieSalesGenerator:
|
|
10
|
+
"""
|
|
11
|
+
A Bayesian-inspired sales data generator using TweedieRegressor as a generative model.
|
|
12
|
+
Merges with the previous M5-like generator but uses Tweedie posterior sampling.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, seed=42):
|
|
16
|
+
self.seed = seed
|
|
17
|
+
np.random.seed(seed)
|
|
18
|
+
self._initialize_parameters()
|
|
19
|
+
self._initialize_hierarchies()
|
|
20
|
+
self.tweedie_models = {}
|
|
21
|
+
self.posterior_samples = {}
|
|
22
|
+
|
|
23
|
+
def _initialize_parameters(self):
|
|
24
|
+
"""Initialize default parameters for data generation."""
|
|
25
|
+
self.params = {
|
|
26
|
+
# Time parameters
|
|
27
|
+
"start_date": "2023-01-01",
|
|
28
|
+
"end_date": "2024-12-31",
|
|
29
|
+
"freq": "D",
|
|
30
|
+
# Scale parameters
|
|
31
|
+
"num_products": 50,
|
|
32
|
+
"num_stores": 5,
|
|
33
|
+
"num_states": 3,
|
|
34
|
+
# Tweedie prior parameters
|
|
35
|
+
"power_prior": (
|
|
36
|
+
1.5,
|
|
37
|
+
0.2,
|
|
38
|
+
), # (mean, std) for normal prior on power parameter
|
|
39
|
+
"alpha_prior": (
|
|
40
|
+
1.0,
|
|
41
|
+
0.5,
|
|
42
|
+
), # (mean, std) for normal prior on regularization
|
|
43
|
+
"dispersion_prior": (1.0, 0.3), # (mean, std) for dispersion
|
|
44
|
+
# Feature parameters
|
|
45
|
+
"n_features": 8,
|
|
46
|
+
"n_informative": 5,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
def _initialize_hierarchies(self):
|
|
50
|
+
"""Initialize hierarchical structures for products and locations."""
|
|
51
|
+
self.hierarchies = {
|
|
52
|
+
"categories": {
|
|
53
|
+
"FOODS": ["FOODS_1", "FOODS_2", "FOODS_3"],
|
|
54
|
+
"HOBBIES": ["HOBBIES_1", "HOBBIES_2"],
|
|
55
|
+
"HOUSEHOLD": ["HOUSEHOLD_1", "HOUSEHOLD_2"],
|
|
56
|
+
},
|
|
57
|
+
"states": ["CA", "TX", "NY"],
|
|
58
|
+
"store_types": ["Supercenter", "Discount", "Neighborhood"],
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
def generate_covariates(self, n_samples, include_temporal=True):
|
|
62
|
+
"""
|
|
63
|
+
Generate realistic covariates for sales data.
|
|
64
|
+
|
|
65
|
+
Parameters:
|
|
66
|
+
-----------
|
|
67
|
+
n_samples : int
|
|
68
|
+
Number of samples to generate
|
|
69
|
+
include_temporal : bool
|
|
70
|
+
Whether to include temporal features
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
--------
|
|
74
|
+
pd.DataFrame
|
|
75
|
+
DataFrame with generated covariates
|
|
76
|
+
"""
|
|
77
|
+
features = {}
|
|
78
|
+
|
|
79
|
+
# Basic features
|
|
80
|
+
features["price"] = np.random.lognormal(2.5, 0.8, n_samples)
|
|
81
|
+
features["promotion"] = np.random.binomial(1, 0.1, n_samples)
|
|
82
|
+
features["competitor_price"] = np.random.lognormal(2.6, 0.7, n_samples)
|
|
83
|
+
features["holiday"] = np.random.binomial(1, 0.05, n_samples)
|
|
84
|
+
|
|
85
|
+
# Store traffic (seasonal)
|
|
86
|
+
if include_temporal:
|
|
87
|
+
t = np.arange(n_samples)
|
|
88
|
+
features["store_traffic"] = (
|
|
89
|
+
100
|
|
90
|
+
+ 20 * np.sin(2 * np.pi * t / 30) # Monthly seasonality
|
|
91
|
+
+ 10 * np.sin(2 * np.pi * t / 7) # Weekly seasonality
|
|
92
|
+
+ np.random.normal(0, 5, n_samples)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Day of week effects
|
|
96
|
+
features["day_of_week"] = t % 7
|
|
97
|
+
features["is_weekend"] = (features["day_of_week"] >= 5).astype(int)
|
|
98
|
+
|
|
99
|
+
# Economic indicators
|
|
100
|
+
features["unemployment_rate"] = np.random.normal(5.0, 1.0, n_samples)
|
|
101
|
+
features["consumer_confidence"] = np.random.normal(100, 15, n_samples)
|
|
102
|
+
|
|
103
|
+
return pd.DataFrame(features)
|
|
104
|
+
|
|
105
|
+
def sample_tweedie_parameters(
|
|
106
|
+
self, n_samples=1000, prior_type="informative"
|
|
107
|
+
):
|
|
108
|
+
"""
|
|
109
|
+
Sample Tweedie parameters from Bayesian priors.
|
|
110
|
+
|
|
111
|
+
Parameters:
|
|
112
|
+
-----------
|
|
113
|
+
n_samples : int
|
|
114
|
+
Number of parameter samples
|
|
115
|
+
prior_type : str
|
|
116
|
+
Type of prior distribution
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
--------
|
|
120
|
+
dict
|
|
121
|
+
Sampled parameters
|
|
122
|
+
"""
|
|
123
|
+
if prior_type == "informative":
|
|
124
|
+
# Informed priors based on retail sales data characteristics
|
|
125
|
+
power_samples = np.random.normal(
|
|
126
|
+
1.6, 0.2, n_samples
|
|
127
|
+
) # Compound Poisson-Gamma
|
|
128
|
+
alpha_samples = np.random.gamma(2, 0.5, n_samples) # Regularization
|
|
129
|
+
dispersion_samples = np.random.gamma(
|
|
130
|
+
3, 0.3, n_samples
|
|
131
|
+
) # Dispersion
|
|
132
|
+
|
|
133
|
+
elif prior_type == "weakly_informative":
|
|
134
|
+
power_samples = np.random.uniform(1.1, 1.9, n_samples)
|
|
135
|
+
alpha_samples = np.random.gamma(1, 1, n_samples)
|
|
136
|
+
dispersion_samples = np.random.gamma(2, 0.5, n_samples)
|
|
137
|
+
|
|
138
|
+
else: # non_informative
|
|
139
|
+
power_samples = np.random.uniform(1.01, 1.99, n_samples)
|
|
140
|
+
alpha_samples = np.random.gamma(0.1, 0.1, n_samples)
|
|
141
|
+
dispersion_samples = np.random.gamma(1, 1, n_samples)
|
|
142
|
+
|
|
143
|
+
# Clip power to valid range
|
|
144
|
+
power_samples = np.clip(power_samples, 1.01, 1.99)
|
|
145
|
+
|
|
146
|
+
self.posterior_samples = {
|
|
147
|
+
"power": power_samples,
|
|
148
|
+
"alpha": alpha_samples,
|
|
149
|
+
"dispersion": dispersion_samples,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return self.posterior_samples
|
|
153
|
+
|
|
154
|
+
def fit_tweedie_generative_model(self, X, y, n_models=10):
|
|
155
|
+
"""
|
|
156
|
+
Fit multiple TweedieRegressor models to capture parameter uncertainty.
|
|
157
|
+
|
|
158
|
+
Parameters:
|
|
159
|
+
-----------
|
|
160
|
+
X : array-like
|
|
161
|
+
Features
|
|
162
|
+
y : array-like
|
|
163
|
+
Target sales
|
|
164
|
+
n_models : int
|
|
165
|
+
Number of models to fit with different parameters
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
--------
|
|
169
|
+
dict
|
|
170
|
+
Fitted models and their parameters
|
|
171
|
+
"""
|
|
172
|
+
print(
|
|
173
|
+
f"Fitting {n_models} TweedieRegressor models for generative sampling..."
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Scale features
|
|
177
|
+
self.scaler = StandardScaler()
|
|
178
|
+
X_scaled = self.scaler.fit_transform(X)
|
|
179
|
+
|
|
180
|
+
# Sample parameters from priors
|
|
181
|
+
param_samples = self.sample_tweedie_parameters(n_models)
|
|
182
|
+
|
|
183
|
+
models = {}
|
|
184
|
+
for i in range(n_models):
|
|
185
|
+
try:
|
|
186
|
+
model = TweedieRegressor(
|
|
187
|
+
power=param_samples["power"][i],
|
|
188
|
+
alpha=param_samples["alpha"][i],
|
|
189
|
+
link="log",
|
|
190
|
+
max_iter=1000,
|
|
191
|
+
tol=1e-4,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
model.fit(X_scaled, y)
|
|
195
|
+
|
|
196
|
+
models[f"model_{i}"] = {
|
|
197
|
+
"model": model,
|
|
198
|
+
"power": param_samples["power"][i],
|
|
199
|
+
"alpha": param_samples["alpha"][i],
|
|
200
|
+
"dispersion": param_samples["dispersion"][i],
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
except Exception as e:
|
|
204
|
+
print(f"Model {i} failed: {e}")
|
|
205
|
+
continue
|
|
206
|
+
|
|
207
|
+
self.tweedie_models = models
|
|
208
|
+
return models
|
|
209
|
+
|
|
210
|
+
def sample_from_tweedie_posterior(
|
|
211
|
+
self, X, n_samples=1000, model_weights=None
|
|
212
|
+
):
|
|
213
|
+
"""
|
|
214
|
+
Generate posterior predictive samples using fitted Tweedie models.
|
|
215
|
+
|
|
216
|
+
Parameters:
|
|
217
|
+
-----------
|
|
218
|
+
X : array-like
|
|
219
|
+
Features for prediction
|
|
220
|
+
n_samples : int
|
|
221
|
+
Number of posterior samples to generate
|
|
222
|
+
model_weights : array-like
|
|
223
|
+
Weights for each model in the ensemble
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
--------
|
|
227
|
+
pd.DataFrame
|
|
228
|
+
Posterior predictive samples
|
|
229
|
+
"""
|
|
230
|
+
if not self.tweedie_models:
|
|
231
|
+
raise ValueError(
|
|
232
|
+
"No models fitted. Call fit_tweedie_generative_model first."
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
X_scaled = self.scaler.transform(X)
|
|
236
|
+
model_names = list(self.tweedie_models.keys())
|
|
237
|
+
|
|
238
|
+
if model_weights is None:
|
|
239
|
+
model_weights = np.ones(len(model_names)) / len(model_names)
|
|
240
|
+
|
|
241
|
+
# Generate samples
|
|
242
|
+
posterior_samples = []
|
|
243
|
+
|
|
244
|
+
for _ in range(n_samples):
|
|
245
|
+
# Sample a model according to weights
|
|
246
|
+
model_idx = np.random.choice(len(model_names), p=model_weights)
|
|
247
|
+
model_name = model_names[model_idx]
|
|
248
|
+
model_info = self.tweedie_models[model_name]
|
|
249
|
+
|
|
250
|
+
# Get prediction (mean of Tweedie distribution)
|
|
251
|
+
mu = model_info["model"].predict(X_scaled)
|
|
252
|
+
|
|
253
|
+
# Sample from Tweedie distribution
|
|
254
|
+
power = model_info["power"]
|
|
255
|
+
dispersion = model_info["dispersion"]
|
|
256
|
+
|
|
257
|
+
# Sample from compound Poisson-Gamma distribution
|
|
258
|
+
samples = self._sample_tweedie_distribution(mu, power, dispersion)
|
|
259
|
+
posterior_samples.append(samples)
|
|
260
|
+
|
|
261
|
+
return pd.DataFrame(
|
|
262
|
+
np.array(posterior_samples).T,
|
|
263
|
+
columns=[f"sample_{i}" for i in range(n_samples)],
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def _sample_tweedie_distribution(self, mu, power, dispersion):
|
|
267
|
+
"""
|
|
268
|
+
Sample from Tweedie compound Poisson-Gamma distribution.
|
|
269
|
+
|
|
270
|
+
Parameters:
|
|
271
|
+
-----------
|
|
272
|
+
mu : array-like
|
|
273
|
+
Mean parameters
|
|
274
|
+
power : float
|
|
275
|
+
Tweedie power parameter
|
|
276
|
+
dispersion : float
|
|
277
|
+
Dispersion parameter
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
--------
|
|
281
|
+
array
|
|
282
|
+
Samples from Tweedie distribution
|
|
283
|
+
"""
|
|
284
|
+
samples = []
|
|
285
|
+
|
|
286
|
+
for mean_val in mu:
|
|
287
|
+
if power == 1: # Poisson
|
|
288
|
+
sample = np.random.poisson(mean_val)
|
|
289
|
+
elif power == 2: # Gamma
|
|
290
|
+
sample = np.random.gamma(mean_val / dispersion, dispersion)
|
|
291
|
+
else: # Compound Poisson-Gamma (1 < power < 2)
|
|
292
|
+
# Parameterization for compound Poisson-Gamma
|
|
293
|
+
lambda_val = (mean_val ** (2 - power)) / (
|
|
294
|
+
(2 - power) * dispersion
|
|
295
|
+
)
|
|
296
|
+
phi = dispersion
|
|
297
|
+
p = (power - 1) / (2 - power)
|
|
298
|
+
|
|
299
|
+
# Number of claims (Poisson)
|
|
300
|
+
N = np.random.poisson(lambda_val)
|
|
301
|
+
|
|
302
|
+
if N > 0:
|
|
303
|
+
# Size of claims (Gamma)
|
|
304
|
+
claim_size = np.random.gamma(
|
|
305
|
+
-p * N, phi * (mean_val ** (power - 1))
|
|
306
|
+
)
|
|
307
|
+
sample = claim_size
|
|
308
|
+
else:
|
|
309
|
+
sample = 0
|
|
310
|
+
|
|
311
|
+
samples.append(max(0, sample)) # Ensure non-negative
|
|
312
|
+
|
|
313
|
+
return np.array(samples)
|
|
314
|
+
|
|
315
|
+
def generate_sales_timeseries(
|
|
316
|
+
self, product_id, store_id, state, n_days=730
|
|
317
|
+
):
|
|
318
|
+
"""
|
|
319
|
+
Generate sales time series using Bayesian Tweedie generative model.
|
|
320
|
+
|
|
321
|
+
Parameters:
|
|
322
|
+
-----------
|
|
323
|
+
product_id : int
|
|
324
|
+
Product identifier
|
|
325
|
+
store_id : int
|
|
326
|
+
Store identifier
|
|
327
|
+
state : str
|
|
328
|
+
State location
|
|
329
|
+
n_days : int
|
|
330
|
+
Number of days to generate
|
|
331
|
+
|
|
332
|
+
Returns:
|
|
333
|
+
--------
|
|
334
|
+
pd.DataFrame
|
|
335
|
+
Generated sales time series with posterior samples
|
|
336
|
+
"""
|
|
337
|
+
# Generate covariates
|
|
338
|
+
covariates = self.generate_covariates(n_days, include_temporal=True)
|
|
339
|
+
|
|
340
|
+
# Add product/store specific features
|
|
341
|
+
covariates["product_id"] = product_id
|
|
342
|
+
covariates["store_id"] = store_id
|
|
343
|
+
covariates["state"] = hash(state) % 100 # Encode state as numeric
|
|
344
|
+
|
|
345
|
+
# Generate dates
|
|
346
|
+
dates = pd.date_range(
|
|
347
|
+
start=self.params["start_date"], periods=n_days, freq="D"
|
|
348
|
+
)
|
|
349
|
+
covariates["date"] = dates
|
|
350
|
+
|
|
351
|
+
# If we have fitted models, use them for generation
|
|
352
|
+
if self.tweedie_models:
|
|
353
|
+
# Use only feature columns for prediction
|
|
354
|
+
feature_cols = [
|
|
355
|
+
col
|
|
356
|
+
for col in covariates.columns
|
|
357
|
+
if col not in ["date", "product_id", "store_id", "state"]
|
|
358
|
+
]
|
|
359
|
+
X_features = covariates[feature_cols]
|
|
360
|
+
|
|
361
|
+
# Generate posterior predictive samples
|
|
362
|
+
posterior_samples = self.sample_from_tweedie_posterior(
|
|
363
|
+
X_features, n_samples=100
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
# Use median as point estimate
|
|
367
|
+
covariates["sales"] = posterior_samples.median(axis=1)
|
|
368
|
+
covariates["sales_std"] = posterior_samples.std(axis=1)
|
|
369
|
+
|
|
370
|
+
# Store samples
|
|
371
|
+
for i in range(
|
|
372
|
+
min(10, posterior_samples.shape[1])
|
|
373
|
+
): # Store first 10 samples
|
|
374
|
+
covariates[f"sales_sample_{i}"] = posterior_samples.iloc[:, i]
|
|
375
|
+
|
|
376
|
+
else:
|
|
377
|
+
# Fallback: simple generative model
|
|
378
|
+
print("No fitted models. Using simple generative approach.")
|
|
379
|
+
base_demand = np.random.gamma(2, 2)
|
|
380
|
+
seasonality = 1 + 0.3 * np.sin(2 * np.pi * np.arange(n_days) / 365)
|
|
381
|
+
covariates["sales"] = np.random.poisson(base_demand * seasonality)
|
|
382
|
+
|
|
383
|
+
# Add product hierarchy
|
|
384
|
+
category, subcategory = self._generate_product_hierarchy(product_id)
|
|
385
|
+
covariates["category"] = category
|
|
386
|
+
covariates["subcategory"] = subcategory
|
|
387
|
+
covariates["store_id"] = f"STORE_{store_id:02d}"
|
|
388
|
+
covariates["product_id"] = f"PROD_{product_id:03d}"
|
|
389
|
+
covariates["state"] = state
|
|
390
|
+
|
|
391
|
+
return covariates
|
|
392
|
+
|
|
393
|
+
def _generate_product_hierarchy(self, product_id):
|
|
394
|
+
"""Generate hierarchical product information."""
|
|
395
|
+
category = np.random.choice(list(self.hierarchies["categories"].keys()))
|
|
396
|
+
subcategory = np.random.choice(self.hierarchies["categories"][category])
|
|
397
|
+
return category, subcategory
|
|
398
|
+
|
|
399
|
+
def generate_complete_dataset(
|
|
400
|
+
self, use_bayesian=True, n_samples_per_series=100
|
|
401
|
+
):
|
|
402
|
+
"""
|
|
403
|
+
Generate complete sales dataset using Bayesian Tweedie approach.
|
|
404
|
+
|
|
405
|
+
Parameters:
|
|
406
|
+
-----------
|
|
407
|
+
use_bayesian : bool
|
|
408
|
+
Whether to use Bayesian Tweedie sampling
|
|
409
|
+
n_samples_per_series : int
|
|
410
|
+
Number of posterior samples per time series
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
--------
|
|
414
|
+
pd.DataFrame
|
|
415
|
+
Complete generated dataset
|
|
416
|
+
"""
|
|
417
|
+
print("Generating complete sales dataset...")
|
|
418
|
+
|
|
419
|
+
all_data = []
|
|
420
|
+
|
|
421
|
+
# Create store-state mapping
|
|
422
|
+
store_state_mapping = {}
|
|
423
|
+
for store_id in range(1, self.params["num_stores"] + 1):
|
|
424
|
+
store_state_mapping[store_id] = np.random.choice(
|
|
425
|
+
self.hierarchies["states"]
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
# If using Bayesian approach, first fit models on some synthetic data
|
|
429
|
+
if use_bayesian:
|
|
430
|
+
print("Fitting Bayesian Tweedie models...")
|
|
431
|
+
# Generate some training data to fit models
|
|
432
|
+
X_train = self.generate_covariates(1000, include_temporal=True)
|
|
433
|
+
y_train = self._generate_simple_sales(X_train)
|
|
434
|
+
self.fit_tweedie_generative_model(X_train, y_train, n_models=20)
|
|
435
|
+
|
|
436
|
+
# Generate data for all products across all stores
|
|
437
|
+
for product_id in range(1, self.params["num_products"] + 1):
|
|
438
|
+
for store_id in range(1, self.params["num_stores"] + 1):
|
|
439
|
+
state = store_state_mapping[store_id]
|
|
440
|
+
|
|
441
|
+
sales_data = self.generate_sales_timeseries(
|
|
442
|
+
product_id, store_id, state, n_days=n_samples_per_series
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
all_data.append(sales_data)
|
|
446
|
+
|
|
447
|
+
complete_data = pd.concat(all_data, ignore_index=True)
|
|
448
|
+
|
|
449
|
+
print(f"Generated dataset with {complete_data.shape[0]} rows")
|
|
450
|
+
return complete_data
|
|
451
|
+
|
|
452
|
+
def _generate_simple_sales(self, covariates):
|
|
453
|
+
"""Generate simple sales for model training."""
|
|
454
|
+
# Simple linear model with noise
|
|
455
|
+
base_effect = (
|
|
456
|
+
10
|
|
457
|
+
+ 2 * covariates["price"]
|
|
458
|
+
+ 5 * covariates["promotion"]
|
|
459
|
+
- 1 * covariates["competitor_price"]
|
|
460
|
+
+ 0.1 * covariates["store_traffic"]
|
|
461
|
+
+ 3 * covariates["holiday"]
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
# Add noise and ensure positive
|
|
465
|
+
sales = np.random.poisson(np.maximum(1, base_effect))
|
|
466
|
+
return sales
|