in python/prophet/serialize.py [0:0]
def model_to_dict(model):
"""Convert a Prophet model to a dictionary suitable for JSON serialization.
Model must be fitted. Skips Stan objects that are not needed for predict.
Can be reversed with model_from_dict.
Parameters
----------
model: Prophet model object.
Returns
-------
dict that can be used to serialize a Prophet model as JSON or loaded back
into a Prophet model.
"""
if model.history is None:
raise ValueError(
"This can only be used to serialize models that have already been fit."
)
model_dict = {
attribute: getattr(model, attribute) for attribute in SIMPLE_ATTRIBUTES
}
# Handle attributes of non-core types
for attribute in PD_SERIES:
if getattr(model, attribute) is None:
model_dict[attribute] = None
else:
model_dict[attribute] = getattr(model, attribute).to_json(
orient='split', date_format='iso'
)
for attribute in PD_TIMESTAMP:
model_dict[attribute] = getattr(model, attribute).timestamp()
for attribute in PD_TIMEDELTA:
model_dict[attribute] = getattr(model, attribute).total_seconds()
for attribute in PD_DATAFRAME:
if getattr(model, attribute) is None:
model_dict[attribute] = None
else:
model_dict[attribute] = getattr(model, attribute).to_json(orient='table', index=False)
for attribute in NP_ARRAY:
model_dict[attribute] = getattr(model, attribute).tolist()
for attribute in ORDEREDDICT:
model_dict[attribute] = [
list(getattr(model, attribute).keys()),
getattr(model, attribute),
]
# Other attributes with special handling
# fit_kwargs -> Transform any numpy types before serializing.
# They do not need to be transformed back on deserializing.
fit_kwargs = deepcopy(model.fit_kwargs)
if 'init' in fit_kwargs:
for k, v in fit_kwargs['init'].items():
if isinstance(v, np.ndarray):
fit_kwargs['init'][k] = v.tolist()
elif isinstance(v, np.floating):
fit_kwargs['init'][k] = float(v)
model_dict['fit_kwargs'] = fit_kwargs
# Params (Dict[str, np.ndarray])
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