-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathtest_basic.py
More file actions
342 lines (286 loc) · 11 KB
/
Copy pathtest_basic.py
File metadata and controls
342 lines (286 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# Copyright 2022 - 2026 The PyMC Labs Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import numpy as np
import pandas as pd
import pymc as pm
import pytest
from arviz import InferenceData, from_dict
from pymc_extras.prior import Prior
from pymc_marketing.clv.models import (
BetaGeoBetaBinomModel,
BetaGeoModel,
GammaGammaModel,
ModifiedBetaGeoModel,
ParetoNBDModel,
ShiftedBetaGeoModel,
)
from pymc_marketing.clv.models.basic import CLVModel
from pymc_marketing.model_builder import DifferentModelError
from tests.clv.conftest import mock_fit_MAP, mock_sample, set_model_fit
class CLVModelTest(CLVModel):
_model_type = "CLVModelTest"
def __init__(
self,
data=None,
model_config=None,
sampler_config: dict | None = None,
):
if data is None:
data = pd.DataFrame({"y": np.random.randn(10)})
super().__init__(
data=data,
model_config=model_config,
sampler_config=sampler_config,
non_distributions=[],
)
@property
def default_model_config(self):
return {
"x": Prior("Normal", mu=0, sigma=1),
}
def _validate_data(self, data: pd.DataFrame) -> None:
"""Validate data for CLVModelTest."""
self._validate_cols(data, required_cols=["y"], must_be_unique=[])
def build_model(self, data: pd.DataFrame | None = None) -> None: # type: ignore[override]
if data is not None:
self._validate_data(data)
self.data = data
elif not hasattr(self, "data") or self.data is None:
raise ValueError(
f"{self._model_type}.build_model() requires data parameter. "
"Either pass data to build_model(data=...) or fit(data=...)"
)
else:
self._validate_data(self.data)
with pm.Model() as self.model:
x = self.model_config["x"].create_variable("x")
pm.Normal("y", mu=x, sigma=1, observed=self.data["y"])
class CLVModelForLoadTest(CLVModelTest):
"""Like CLVModelTest but does not invent random ``data`` when ``data`` is omitted."""
_model_type = "CLVModelForLoadTest"
def __init__(
self,
data=None,
model_config=None,
sampler_config: dict | None = None,
):
CLVModel.__init__(
self,
data=data,
model_config=model_config,
sampler_config=sampler_config,
non_distributions=[],
)
@pytest.fixture(scope="module")
def posterior():
# Create a random numpy array for posterior samples
posterior_samples = np.random.randn(
4, 100, 2
) # shape convention: (chain, draw, *shape)
# Create a dictionary for posterior
posterior_dict = {"theta": posterior_samples}
return from_dict(posterior=posterior_dict)
class TestCLVModel:
def test_repr(self):
model = CLVModelTest()
assert model.__repr__() == "CLVModelTest"
model.build_model()
assert model.__repr__() == "CLVModelTest\nx ~ Normal(0, 1)\ny ~ Normal(x, 1)"
def test_fit_mcmc(self, mocker):
model = CLVModelTest()
mocker.patch("pymc.sample", mock_sample)
idata = model.fit(
tune=5,
chains=2,
draws=10,
compute_convergence_checks=False,
)
assert isinstance(idata, InferenceData)
assert len(idata.posterior.chain) == 2
assert len(idata.posterior.draw) == 10
assert model.fit_result is idata.posterior
def test_fit_map(self, mocker):
model = CLVModelTest()
mocker.patch("pymc_marketing.clv.models.basic.CLVModel._fit_MAP", mock_fit_MAP)
idata = model.fit(method="map")
assert isinstance(idata, InferenceData)
assert len(idata.posterior.chain) == 1
assert len(idata.posterior.draw) == 1
assert model.fit_result is idata.posterior
# Check that summary only includes single value
summ = model.fit_summary()
assert isinstance(summ, pd.Series)
assert summ.name == "value"
def test_fit_demz(self, mocker):
model = CLVModelTest()
mocker.patch("pymc.sample", mock_sample)
idata = model.fit(
method="demz",
tune=5,
chains=2,
draws=10,
compute_convergence_checks=False,
)
assert isinstance(idata, InferenceData)
assert len(idata.posterior.chain) == 2
assert len(idata.posterior.draw) == 10
assert model.fit_result is idata.posterior
def test_fit_advi(self, mocker):
model = CLVModelTest()
# mocker.patch("pymc.sample", mock_sample)
idata = model.fit(
method="advi",
tune=5,
chains=2,
draws=10,
)
assert isinstance(idata, InferenceData)
assert len(idata.posterior.chain) == 1
assert len(idata.posterior.draw) == 10
def test_fit_advi_with_wrong_chains_advi_kwargs(self, mocker):
model = CLVModelTest()
with pytest.warns(
UserWarning,
match=r"The 'chains' parameter must be 1 with 'advi'. Sampling only 1 chain despite the provided parameter.", # noqa: E501
):
model.fit(
method="advi",
tune=5,
chains=2,
draws=10,
)
def test_wrong_method(self):
model = CLVModelTest()
with pytest.raises(
ValueError,
match=r"Fit method options are \['mcmc', 'map', 'demz', 'advi', 'fullrank_advi'\], got: wrong_method",
):
model.fit(method="wrong_method")
def test_fit_exception(self, mock_pymc_sample):
model = CLVModelTest()
with pytest.warns(
DeprecationWarning,
match=(
"'fit_method' is deprecated and will be removed in version 1.0. "
"Use 'method' instead."
),
):
model.fit(fit_method="mcmc")
def test_load(self, mocker):
model = CLVModelTest()
mocker.patch("pymc.sample", mock_sample)
model.fit(tune=0, chains=2, draws=5)
model.save("test_model")
model2 = model.load("test_model")
assert model2.fit_result is not None
# TODO: Add this to the model_builder.py load method?
model2.build_model()
assert model2.model is not None
os.remove("test_model")
def test_load_from_idata_without_fit_data_warns(self, mocker):
mocker.patch("pymc.sample", mock_sample)
model = CLVModelForLoadTest()
data = pd.DataFrame({"y": np.arange(10, dtype=float)})
model.fit(data=data, tune=0, chains=2, draws=5)
idata = model.idata.copy()
assert "fit_data" in idata
del idata.fit_data
with pytest.warns(UserWarning, match="fit_data used for training"):
loaded = CLVModelForLoadTest.load_from_idata(idata)
assert isinstance(loaded, CLVModelForLoadTest)
assert loaded.idata is idata
assert not hasattr(loaded, "model")
assert not hasattr(loaded, "data")
def test_default_sampler_config(self):
model = CLVModelTest()
assert model.sampler_config == {}
def test_fit_summary_for_mcmc(self, mocker):
model = CLVModelTest()
mocker.patch("pymc.sample", mock_sample)
model.fit(tune=0, chains=2, draws=5)
summ = model.fit_summary()
assert isinstance(summ, pd.DataFrame)
def test_serializable_model_config(self):
model = CLVModelTest()
serializable_config = model._serializable_model_config
assert isinstance(serializable_config, dict)
assert serializable_config == model.model_config
def test_fail_id_after_load(self, mocker, monkeypatch):
# This is the new behavior for the property
def mock_property(self):
return "for sure not correct id"
# Now create an instance of MyClass
mock_basic = CLVModelTest()
mocker.patch("pymc.sample", mock_sample)
mock_basic.fit(tune=0, chains=2, draws=5)
mock_basic.save("test_model")
# Apply the monkeypatch for the property
monkeypatch.setattr(CLVModelTest, "id", property(mock_property))
with pytest.raises(
DifferentModelError,
match=r"The file 'test_model'",
):
CLVModelTest.load("test_model")
os.remove("test_model")
def test_thin_fit_result(self):
data = pd.DataFrame(dict(y=[-3, -2, -1]))
model = CLVModelTest(data=data)
model.build_model()
fake_idata = from_dict(dict(x=np.random.normal(size=(4, 1000))))
set_model_fit(model, fake_idata)
thin_model = model.thin_fit_result(keep_every=20)
assert thin_model is not model
assert thin_model.idata is not model.idata
assert len(thin_model.idata.posterior["x"].chain) == 4
assert len(thin_model.idata.posterior["x"].draw) == 50
assert thin_model.data is not model.data
assert np.all(thin_model.data == model.data)
def test_model_config_warns(self) -> None:
model_config = {
"x": {"dist": "StudentT", "kwargs": {"mu": 0, "sigma": 5, "nu": 15}},
}
with pytest.warns(DeprecationWarning, match=r"x is automatically"):
model = CLVModelTest(model_config=model_config)
assert model.model_config == {
"x": Prior("StudentT", mu=0, sigma=5, nu=15),
}
def test_validate_cols_reports_all_missing_columns(self):
"""Test _validate_cols raises a single ValueError listing all missing columns."""
required = ("customer_id", "frequency", "recency", "T")
data = pd.DataFrame(
{
"customer_id": [1, 2, 3],
"frequency": [1, 2, 3],
}
)
expected_error_msg = r"The following required columns are missing from the input data: \['T', 'recency'\]"
with pytest.raises(ValueError, match=expected_error_msg):
CLVModel._validate_cols(data=data, required_cols=required)
@pytest.mark.parametrize(
"model_cls",
[
BetaGeoModel,
ParetoNBDModel,
ModifiedBetaGeoModel,
BetaGeoBetaBinomModel,
ShiftedBetaGeoModel,
GammaGammaModel,
],
)
def test_build_model_without_data_raises_value_error(model_cls):
"""Test that build_model() without data raises ValueError when data is unspecified."""
model = model_cls()
with pytest.raises(ValueError, match="requires data parameter"):
model.build_model()