Prophet初探

先给看个酷炫的图
enter image description here

安装

官方的安装教程在这里但是,按照官方的安装教程是安装不成功的说起来都是痛,
以下是正确的安装步骤(python3.5 64位环境):

  1. 安装C++编译器]Visual C++ Build Tools
  2. 安装pystan 推荐清华源(使用pip install pystan -i https://pypi.tuna.tsinghua.edu.cn/simple) 手打的,不保证对。
  3. 安装fbprophet,齐活。

快速使用

对原理有兴趣的,可以戳这里暂时我只把它当成一个黑箱子使用。
首先是数据,这里选用的是随机生成的web统计数据,首先我们加载数据:

1
2
3
4
5
6
7
8
# -*- encoding:utf-8 -*-
import pandas as pd
import numpy as np
from fbprophet import Prophet
import matplotlib.pyplot as plt
data_file = "data_trend.csv"
df = pd.read_csv(data_file, encoding="utf-8")
df.head()

enter image description here
主要有上面这几个字段。
我们想看看浏览次数随时间的变化情况
单独取出时段独立访客数据。另外我们的数据是倒序的,还需要按时间顺序回来,先画个图看看。

1
2
3
4
df_pv = df[["时段", "独立访客"]]
sort_df = df_pv.sort_values(by="时段")
sort_df.set_index("时段").plot()
plt.show()

enter image description here
能大体看出独立访客数随时间的变化趋势,但是这个图的图例显示不正常,在开头再加上这两行

1
2
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False

简单来说就是定义图的字体。

预测

prophet的API有点类似scikit-learn,常规流程,先fit数据,然后predict新的趋势。
首先我们修改column名称创建第一个预测模型

1
2
3
4
sort_df.columns = ["ds", "y"]
sort_df['y'] = np.log(sort_df['y'])
m1 = Prophet()
m1.fit(sort_df)

使用make_future_dataframe告诉prophet需要预测多久以后的数据,在这个例子中,我们选择预测未来一年的独立访客数。

1
2
3
futures1 = m1.make_future_dataframe(periods=365)
forecast1 = m1.predict(futures1)
forecast1[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

forecast1 是dataframe格式的数据,如下:
enter image description here
Prophet在做预测的时候做了log处理,还原后数据如下:

1
2
3
4
5
6
7
8
9
print(np.exp(forecast1[['yhat', 'yhat_lower', 'yhat_upper']].tail()))
console:
yhat yhat_lower yhat_upper
630 10584.491634 212.320650 647084.467489
631 11077.641554 218.018125 671727.514255
632 11121.285237 219.600455 658814.011148
633 10834.162204 215.267186 660137.259109
634 10904.075380 201.501246 678710.749914

作图

1
m1.plot(forecast1)

enter image description here
略微有点崩溃,猜测原因是数据量太小,另外波动有异常,所以预测的最大最小值差距比较大。

1
m1.plot_components(forecast1)

enter image description here
能看出天还有星期的一个趋势。基本介绍就到这了,要继续研究的可以戳这里
Have Fun~~