【问题标题】:Forecasting with time series in python在 python 中使用时间序列进行预测
【发布时间】:2015-10-01 12:13:37
【问题描述】:

我需要你们的帮助。 当 X(天)代表时间时,我实际上想预测变量 Y(c_start)的下一个值。 正如您在图片中看到的,我有属性“c_start”的值,我想预测接下来 7 天的下一个“c_start”值(例如)。 有人可以帮我吗?

谢谢各位!

【问题讨论】:

  • 请发布原始输入数据,编码您的努力和所需的输出,而不是图像
  • 您可以在第一张图片中看到原始输入数据
  • @issouluch 需要原始 csv 数据文件。您可以使用 Dropbox 共享链接或 Google 驱动程序上传它。
  • 对不起,但我(可能还有其他人)不会从图像中转录您的输入数据并从中重建 df,如果您需要帮助,那么您需要帮助我们以便我们帮助你
  • 在我的 df 中,我们需要预测未来的唯一列是:“day”(第 2 个)和“c_start”(第 6 个),其他的没有用。我不明白你的问题

标签: python pandas scikit-learn time-series


【解决方案1】:

检查样本组中的 ARMA 模型:

import pandas as pd
from pandas.tseries.offsets import *
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

csv_file = '/home/Jian/Downloads/analyse vtr.csv'
df = pd.read_csv(csv_file, index_col=[0], sep='\t')
grouped = df.groupby('adserver_id')
group = list(grouped)[0][1]

ts_data = pd.TimeSeries(group.c_start.values, index=pd.to_datetime(group.day))
# positive-valued process, looks non-stationary
# simple way is to do a log transform
fig, axes = plt.subplots(figsize=(10,8), nrows=3)
ts_data.plot(ax=axes[0])

ts_log_data = np.log(ts_data)
ts_log_data.plot(ax=axes[1], style='b-', label='actual')

# in-sample fit
# ===================================
model = sm.tsa.ARMA(ts_log_data, order=(1,1)).fit()
print(model.params)

y_pred = model.predict(ts_log_data.index[0].isoformat(), ts_log_data.index[-1].isoformat())
y_pred.plot(ax=axes[1], style='r--', label='in-sample fit')

y_resid = model.resid
y_resid.plot(ax=axes[2])

# out-sample predict
# ===================================
start_date = ts_log_data.index[-1] + Day(1)
end_date = ts_log_data.index[-1] + Day(7)

y_forecast = model.predict(start_date.isoformat(), end_date.isoformat())

print(y_forecast)


2015-07-11    7.5526
2015-07-12    7.4584
2015-07-13    7.3830
2015-07-14    7.3224
2015-07-15    7.2739
2015-07-16    7.2349
2015-07-17    7.2037
Freq: D, dtype: float64


# NOTE: this step introduces bias, it is used here just for simplicity
# E[exp(x)] != exp[E[x]]
print(np.exp(y_forecast))

2015-07-11    1905.6328
2015-07-12    1734.4442
2015-07-13    1608.3362
2015-07-14    1513.8595
2015-07-15    1442.1183
2015-07-16    1387.0486
2015-07-17    1344.4080
Freq: D, dtype: float64

为每个子组运行 ARMA 模型(非常耗时):

import pandas as pd
from pandas.tseries.offsets import *
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

csv_file = '/home/Jian/Downloads/analyse vtr.csv'
df = pd.read_csv(csv_file, index_col=[0], sep='\t')
grouped = df.groupby('adserver_id')


def forecast_func(group):
    ts_log_data = np.log(pd.TimeSeries(group.c_start.values, index=pd.to_datetime(group.day)))
    # for some group, it raise convergence issue
    try:
        model = sm.tsa.ARMA(ts_log_data, order=(1,1)).fit()
        start_date = ts_log_data.index[-1] + Day(1)
        end_date = ts_log_data.index[-1] + Day(7)
        y_forecast = model.predict(start_date.isoformat(), end_date.isoformat())
        return pd.Series(np.exp(y_forecast).values, np.arange(1, 8))
    except Exception:
        pass


result = df.groupby('adserver_id').apply(forecast_func)

替代模型:为了快速计算,考虑指数平滑;另外,我看到数据看起来像是一个具有时变 Possion 分布的正值过程,可以考虑使用pymc 模块的状态空间模型。

【讨论】:

  • 非常感谢@JianxunLi 的帮助。它似乎工作得很好。祝你有美好的一天:)
  • @issouluch 不客气。很高兴它有帮助。
  • 当然有帮助!您知道这个 ARMA 方法中的“顺序”(sm.tsa.ARMA(ts_log_data, order=(1,1))) 是什么意思吗?如何更改它以获得其他结果?
  • 嗨,我正在我的数据集上尝试上面的代码。读取 CSV 文件时;列名被删除。当我做 groupby 时,它会抛出一个 keyerror。请告诉我,这一步是如何完成的
  • module 'pandas' has no attribute 'TimeSeries' :(
猜你喜欢
  • 2020-09-07
  • 2016-01-04
  • 2012-12-25
  • 2017-10-03
  • 2019-05-22
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
相关资源
最近更新 更多