【问题标题】:how to correctly plot regression output with right datetime index on x-axis in matplotlib?如何在matplotlib的x轴上正确绘制回归输出与正确的日期时间索引?
【发布时间】:2021-03-19 10:49:17
【问题描述】:

我有空气污染时间序列数据,需要进行远期估计。为此,我使用来自scikit-learn 的随机森林回归器进行预测,并且我想可视化预测输出,但我无法可视化回归输出,其中 x 轴必须显示正确的时间索引。可以建议我如何为下面的回归方法获得更好的可视化?有没有更好的方法来实现这一点?有什么想法吗?

我的尝试

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor

url = "https://gist.githubusercontent.com/jerry-shad/36912907ba8660e11cd27be0d3e30639/raw/424f0891dc46d96cd5f867f3d2697777ac984f68/pollution.csv"
df = pd.read_csv(url, parse_dates=['date'])
df.date = pd.DatetimeIndex(df.date)
# df.sort_values(by='date').reset_index(drop=True)
df.drop(columns=['Unnamed: 0'],axis=1,inplace=True)
resultsDict={}
predictionsDict={}

split_date ='2017-12-01'
df_training = df.loc[df.date <= split_date]
df_test = df.loc[df.date > split_date]

## exclude pollution_index columns from training and testing data
df_tr = df_training.drop(['pollution_index'],axis=1)
df_te = df_test.drop(['pollution_index'],axis=1)

## scaling features
scaler = StandardScaler() 
scaler.fit(df_tr)
X_train = scaler.transform(df_tr)  
y_train = df_training['pollution_index']
X_test = scaler.transform(df_te)
y_test = df_test['pollution_index']

X_train_df = pd.DataFrame(X_train,columns=df_tr.columns)
X_test_df = pd.DataFrame(X_test,columns=df_te.columns)

reg = RandomForestRegressor(max_depth=2, random_state=0)
reg.fit(X_train, y_train)
yhat = reg.predict(X_test)
resultsDict['Randomforest'] = evaluate(df_test['eyci'], yhat)
predictionsDict['Randomforest'] = yhat

## print out prediction from RandomForest
print(predictionsDict['Randomforest'])
plt.plot(df_test['pollution_index'].values , label='Original')
plt.plot(yhat,color='red',label='predicted')
plt.legend()

当前尝试的输出

这是above 尝试的输出:

在这次尝试中,我尝试使用随机森林回归器进行回归,并打算制作简单的绘图,但绘图没有在 x 轴上显示时间?为什么?有谁知道如何做到这一点?有什么想法吗?谢谢

想要的情节

理想情况下,在训练模型后,我想进行前向周期估计,这是我想从上述尝试中得出的可能图:

谁能向我建议在回归输出上进行正确可视化的可能方法?有什么想法吗?

【问题讨论】:

标签: python matplotlib scikit-learn


【解决方案1】:

您需要将日期明确提供给matplotlib.pyplot.plot()

plt.plot(df_test['date'],df_test['pollution_index'].values , label='Original')
plt.plot(df_test['date'],yhat,color='red',label='predicted')

您还可以使用pandas 中基于matplotlib 的绘图功能:

df_test['yhat'] = yhat
df_test.plot(x='date',y=['pollution_index','yhat'])

它会自动绘制标题、x/y 标签和图例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2015-06-01
    • 2013-12-12
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多