You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Prophet模型遇NaN值报错,但数据集无缺失的问题排查

解决Prophet回归器报错NaN的问题

问题根源

报错的核心原因不在原selection数据集,而是出在future数据框的处理上:

  • make_future_dataframe(periods=2, freq='M')会生成比原selection多2行的时间序列(对应未来2个月份)
  • 你直接把selection的回归器列赋值给future时,新增的2行没有对应数据,会自动填充为NaN,导致predict时触发Prophet的NaN检查报错
  • 你检查selection['Peak_viewers']确实无NaN,但future里的回归器列存在NaN,这才是报错的真正原因

解决方案

根据需求选择以下两种处理方式:

方式一:仅对已有历史数据做预测(不新增未来周期)

如果不需要预测未来2个周期,去掉periods=2参数,让future和selection的时间范围完全一致:

model = Prophet()
model.add_regressor('Peak_viewers')
model.add_regressor('Streamers')
model.add_regressor('Avg_channels')

model.fit(selection)
# 生成与原数据时间范围匹配的future数据框
future = model.make_future_dataframe(freq='M')
future['Peak_viewers'] = selection['Peak_viewers']
future['Streamers'] = selection['Streamers']
future['Avg_channels'] = selection['Avg_channels']

forecast = model.predict(future)
fig = model.plot(forecast)

方式二:预测未来周期,提前填充回归器的未来值

如果需要预测未来2个周期,必须为新增的2行回归器列填充合理值(示例用历史均值,也可替换为单独训练模型预测的精准值):

model = Prophet()
model.add_regressor('Peak_viewers')
model.add_regressor('Streamers')
model.add_regressor('Avg_channels')

model.fit(selection)
future = model.make_future_dataframe(periods=2, freq='M')

# 填充历史数据部分
future.loc[:len(selection)-1, 'Peak_viewers'] = selection['Peak_viewers'].values
future.loc[:len(selection)-1, 'Streamers'] = selection['Streamers'].values
future.loc[:len(selection)-1, 'Avg_channels'] = selection['Avg_channels'].values

# 为未来2行填充历史均值(可根据需求替换为更精准的预测逻辑)
future.loc[len(selection):, 'Peak_viewers'] = selection['Peak_viewers'].mean()
future.loc[len(selection):, 'Streamers'] = selection['Streamers'].mean()
future.loc[len(selection):, 'Avg_channels'] = selection['Avg_channels'].mean()

forecast = model.predict(future)
fig = model.plot(forecast)

验证方法

可以在赋值后检查future的NaN情况,确认问题:

print(future['Peak_viewers'].isnull().any())  # 会返回True,对应新增的2行

内容的提问来源于stack exchange,提问作者BlindSocket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:30:33