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

如何用Python中Facebook Prophet获取折线方程与R-squared值?

使用Facebook Prophet获取模型趋势方程与R-squared值

计算R-squared值

Prophet没有直接内置R²指标,你可以用模型的预测结果和原始数据手动计算:

  1. 拟合模型后,生成训练集对应的预测结果
  2. 提取真实值和预测值,用sklearn.metrics.r2_score计算R²

代码示例:

from prophet import Prophet
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np

# 准备示例数据
df = pd.DataFrame({
    'ds': pd.date_range(start='2023-01-01', periods=100),
    'y': [i + np.random.normal(0, 2) for i in range(100)]
})

# 拟合Prophet模型
model = Prophet()
model.fit(df)

# 生成训练集的预测(periods=0表示不预测未来)
future = model.make_future_dataframe(periods=0)
forecast = model.predict(future)

# 计算R-squared
r2 = r2_score(df['y'], forecast['yhat'])
print(f"R-squared值: {r2:.4f}")

获取趋势分段方程

注意:Prophet默认的趋势是分段线性趋势,不是单一全局的斜率截距方程——它会根据数据中的突变点(changepoints)将时间序列分成多个线性段,每个段有独立的斜率和截距。你可以通过以下两种方式提取这些分段的方程:

方式1:直接从模型参数提取

拟合后的模型存储了趋势的关键参数,你可以直接读取并计算各分段的斜率和截距:

# 提取趋势核心参数
changepoints = model.changepoints  # 突变点日期列表
initial_slope = model.params['k'][0]  # 初始斜率
initial_intercept = model.params['m'][0]  # 初始截距
slope_changes = model.params['delta'][:, 0]  # 每个突变点后的斜率变化量

# 计算每个分段的斜率
segment_slopes = [initial_slope + sum(slope_changes[:i+1]) for i in range(len(slope_changes))]
segment_slopes.insert(0, initial_slope)  # 第一个分段的斜率就是初始斜率

# 输出各分段的线性方程
print("分段趋势方程:")
for i in range(len(changepoints) + 1):
    # 确定当前分段的时间范围
    if i == 0:
        start_date = df['ds'].min()
        end_date = changepoints[0] if len(changepoints) > 0 else df['ds'].max()
    elif i == len(changepoints):
        start_date = changepoints[-1]
        end_date = df['ds'].max()
    else:
        start_date = changepoints[i-1]
        end_date = changepoints[i]
    
    # Prophet将日期转换为从2010-01-01开始的天数,这里计算分段的截距
    start_days = (start_date - pd.to_datetime('2010-01-01')).days
    segment_intercept = initial_intercept + segment_slopes[i] * (-start_days)
    
    print(f"时间段 {start_date.date()} 至 {end_date.date()}:y = {segment_slopes[i]:.4f}*x + {segment_intercept:.4f}")

方式2:用utilities工具包解析趋势

Prophet的prophet.utilities模块提供了piecewise_linear_trend函数,可以直接生成趋势的分段计算函数,方便你直接计算任意日期的趋势值:

from prophet.utilities import piecewise_linear_trend

# 整理趋势参数
trend_params = {
    'changepoints': model.changepoints,
    'k': model.params['k'][0],
    'm': model.params['m'][0],
    'delta': model.params['delta'][:, 0]
}

# 生成分段趋势计算函数
trend_calculator = piecewise_linear_trend(**trend_params)

# 示例:计算指定日期的趋势值
test_date = pd.to_datetime('2023-03-01')
test_days = (test_date - pd.to_datetime('2010-01-01')).days
trend_value = trend_calculator(test_days)
print(f"{test_date.date()} 的趋势值:{trend_value:.4f}")

如果你的模型使用了逻辑增长趋势(growth='logistic'),方程形式会变为逻辑函数,需要提取cap(上限)、floor(下限)等参数进行解析,核心思路和上面一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:55:33