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

PyCaret时间序列在Streamlit中无法同时显示样本内外绘图

PyCaret时间序列+Streamlit样本内绘图不显示问题解决

在使用PyCaret时间序列模块开发Streamlit应用做数据实验时,遇到样本外(out-of-sample)绘图正常显示,但样本内(insample)绘图无法显示的问题,原代码如下:

from pycaret.time_series import TSForecastingExperiment
import streamlit as st
exp_auto = TSForecastingExperiment()
def run_pycaret(df, target='qty', horizon=12):
    exp_auto.setup(
        data=df, target=target, fh=horizon, enforce_exogenous=False,
        numeric_imputation_target="ffill", numeric_imputation_exogenous="ffill",
        scale_target="minmax",
        scale_exogenous="minmax",
        fold_strategy="expanding",
        session_id=42, verbose=False)
    best = exp_auto.compare_models(sort="mape", turbo=False, verbose=False)
    metrics = exp_auto.pull()
    insample = exp_auto.plot_model(best, plot='insample',display_format='streamlit')
    outsample = exp_auto.plot_model(best, plot='forecast', display_format='streamlit')
    return best, metrics, insample, outsample


if st.button("Run Time series models:"):
    best, metrics, insample, outsample = run_pycaret(df_exog, horizon=steps)

    st.write(metrics)
    # Plot graph
    col1_ts_exp, col2_ts_exp = st.columns(2)
    with col1_ts_exp:
        insample
    with col2_ts_exp:
        outsample

实验结果仅显示样本外绘图:
实验结果图

问题原因

PyCaret的plot_model方法在指定display_format='streamlit'时,针对不同绘图类型的处理逻辑存在差异:

  • 对于forecast类型的绘图,方法会返回可赋值的绘图对象;
  • 对于insample类型的绘图,方法会直接在当前Streamlit上下文渲染,不会返回有效对象,赋值给insample的实际是None,因此无法显示。

解决方案

不要将plot_model的结果赋值给变量,而是直接在对应的Streamlit列上下文里调用plot_model方法。修改后的代码如下:

from pycaret.time_series import TSForecastingExperiment
import streamlit as st
exp_auto = TSForecastingExperiment()
def run_pycaret(df, target='qty', horizon=12):
    exp_auto.setup(
        data=df, target=target, fh=horizon, enforce_exogenous=False,
        numeric_imputation_target="ffill", numeric_imputation_exogenous="ffill",
        scale_target="minmax",
        scale_exogenous="minmax",
        fold_strategy="expanding",
        session_id=42, verbose=False)
    best = exp_auto.compare_models(sort="mape", turbo=False, verbose=False)
    metrics = exp_auto.pull()
    # 不再赋值insample和outsample,直接在Streamlit上下文渲染
    return best, metrics


if st.button("Run Time series models:"):
    best, metrics = run_pycaret(df_exog, horizon=steps)

    st.write(metrics)
    # Plot graph
    col1_ts_exp, col2_ts_exp = st.columns(2)
    with col1_ts_exp:
        st.subheader("样本内拟合图")
        exp_auto.plot_model(best, plot='insample', display_format='streamlit')
    with col2_ts_exp:
        st.subheader("样本外预测图")
        exp_auto.plot_model(best, plot='forecast', display_format='streamlit')

修改后,样本内和样本外的绘图就能正常在对应的列中显示。

内容的提问来源于stack exchange,提问作者Sam.H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:28:31