Prophet温启动拟合示例代码运行崩溃问题求助
Prophet 1.1.1温启动报错解决方案
问题描述
使用Prophet官方温启动示例代码时,运行温启动步骤出现AttributeError: 'list' object has no attribute 'tolist'错误,当前Prophet版本为1.1.1,因项目依赖限制无法升级。
复现代码
from prophet import Prophet import numpy as np import pandas as pd def warm_start_params(m): """ Retrieve parameters from a trained model in the format used to initialize a new Stan model. Note that the new Stan model must have these same settings: n_changepoints, seasonality features, mcmc sampling for the retrieved parameters to be valid for the new model. Parameters ---------- m: A trained model of the Prophet class. Returns ------- A Dictionary containing retrieved parameters of m. """ res = {} for pname in ['k', 'm', 'sigma_obs']: if m.mcmc_samples == 0: res[pname] = m.params[pname][0][0] else: res[pname] = np.mean(m.params[pname]) for pname in ['delta', 'beta']: if m.mcmc_samples == 0: res[pname] = m.params[pname][0] else: res[pname] = np.mean(m.params[pname], axis=0) return res df = pd.read_csv('example_wp_log_peyton_manning.csv') df1 = df.loc[df['ds'] < '2016-01-19', :] # 除最后一天外的所有数据 m1 = Prophet().fit(df1) # 基于除最后一天外的数据训练模型 %timeit m2 = Prophet().fit(df) # 从头训练完整数据 %timeit m2 = Prophet().fit(df, init=warm_start_params(m1)) # 原报错的温启动行
报错信息
11:40:57 - cmdstanpy - INFO - Chain [1] start processing 11:40:58 - cmdstanpy - INFO - Chain [1] done processing ...(省略重复日志) 1.09 s ± 85.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[11], line 36 32 m1 = Prophet().fit(df1) # A model fit to all data except the last day 35 get_ipython().run_line_magic('timeit', 'm2 = Prophet().fit(df) # Adding the last day, fitting from scratch') ---> 36 get_ipython().run_line_magic('timeit', 'm2 = Prophet().fit(df, init=warm_start_params(m1)) # Adding the last day, warm-starting from m1') ...(省略中间调用栈) File /root/miniconda3/lib/python3.9/site-packages/prophet/models.py:154, in CmdStanPyBackend.prepare_data(init, data) 153 'trend_indicator': data['trend_indicator'], --> 154 'y': data['y'].tolist(), 155 't': data['t'].tolist(), 156 'cap': data['cap'].tolist(), AttributeError: 'list' object has no attribute 'tolist'
问题原因
Prophet 1.1.1版本的CmdStanPyBackend.fit方法存在逻辑错误:当传入init参数时,会将已处理完成的stan_data(其中y等字段已转为list)再次传入prepare_data方法,而该方法仍尝试调用tolist(),触发属性错误。
解决方案
将温启动调用中的init参数替换为inits参数,直接传入预训练模型的参数,绕过错误的参数处理逻辑:
%timeit m2 = Prophet().fit(df, inits=warm_start_params(m1)) # 修改后的温启动行
同时确保warm_start_params函数返回的参数格式符合要求:
k、m、sigma_obs为标量delta、beta为一维数组
内容的提问来源于stack exchange,提问作者gsamaras
相关产品推荐
相关产品推荐

