Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion python/prophet/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,19 @@ def model_to_dict(model: Prophet) -> dict[str, Any]:
model_dict['params'] = {k: v.tolist() for k, v in model.params.items()}
# Attributes that are skipped: stan_fit, stan_backend
model_dict["__prophet_version"] = __version__
return model_dict
return _to_builtin_types(model_dict)


def _to_builtin_types(value: Any) -> Any:
"""Replace numpy scalars, e.g. an np.int64 passed as n_changepoints or as
a seasonality's fourier_order, with the Python types json can write."""
if isinstance(value, np.generic):
return value.item()
if isinstance(value, dict):
return type(value)((k, _to_builtin_types(v)) for k, v in value.items())
if isinstance(value, list):
return [_to_builtin_types(v) for v in value]
return value


def model_to_json(model: Prophet) -> str:
Expand Down
29 changes: 29 additions & 0 deletions python/prophet/tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,35 @@ def test_serialize_model_with_regressor_predictor(self, tmp_path, backend):
future["extra"] = np.linspace(20, 22, 5)
m2.predict(future)

def test_serialize_numpy_scalar_arguments(self, daily_univariate_ts, backend):
# Settings read from numpy arrays or dataframe rows, e.g. after a
# hyperparameter search, arrive as numpy scalars
df = daily_univariate_ts.head(daily_univariate_ts.shape[0] - 30).copy()
df["extra"] = np.arange(df.shape[0]) % 7
m = Prophet(
n_changepoints=np.int64(10),
uncertainty_samples=np.int64(100),
stan_backend=backend,
)
m.add_seasonality(name="monthly", period=30.5, fourier_order=np.int64(5))
m.add_regressor("extra", prior_scale=np.int64(1))
m.fit(df)

m2 = model_from_json(model_to_json(m))

assert m2.n_changepoints == 10
assert m2.uncertainty_samples == 100
assert m2.seasonalities["monthly"]["fourier_order"] == 5
assert m2.extra_regressors["extra"]["prior_scale"] == 1
# serializing leaves the model's own settings as they were
assert isinstance(m.seasonalities["monthly"]["fourier_order"], np.int64)

future = m.make_future_dataframe(5)
future["extra"] = np.arange(future.shape[0]) % 7
fcst = m.predict(future)
fcst2 = m2.predict(future)
assert np.array_equal(fcst["yhat"].values, fcst2["yhat"].values)

def test_backwards_compatibility(self):
old_versions = {
"0.6.1.dev0": (29.3669923968994, "fb"),
Expand Down