# 快速开始
先知遵循sklearn模型API。我们创建一个Prophet类的实例,然后调用它fit和predict方法。
先知的输入总是dataframe格式的两列:ds和y(列名必须是ds和y)。ds列必须包含一个日期或日期时间,
y列必须是数字,代表我们要预测的测量
例如:让我们来看看佩顿曼宁的维基百科页面的每日网页浏览时间。它提供了一个很好的例子,因为它说明了先知的一些功能,如多个季节性,不断变化的增长率,以及模拟特殊日子的能力(如曼宁季后赛和超级碗表演)。CSV数据可以[在这里下载](https://github.com/facebookincubator/prophet/blob/master/examples/example_wp_peyton_manning.csv)
首先我们将导入数据并对y变量进行log对数变换。
import pandas as pd
import numpy as np
from fbprophet import Prophet
%matplotlib inline
df = pd.read_csv('./examples/example_wp_peyton_manning.csv')
df['y'] = np.log(df['y'])
#df['ds']=pd.to_datetime(df['ds'])
df.head()
#df.tail()
.dataframe thead tr:only-child th {
text-align: right;
}
.dataframe thead th {
text-align: left;
}
.dataframe tbody tr th {
vertical-align: top;
}
ds | y | |
---|---|---|
0 | 2007-12-10 | 9.590761 |
1 | 2007-12-11 | 8.519590 |
2 | 2007-12-12 | 8.183677 |
3 | 2007-12-13 | 8.072467 |
4 | 2007-12-14 | 7.893572 |
我们通过实例化一个新的Prophet对象来拟合模型。预测过程的任何设置都
将传递给构造函数,然后你调用它的fit方法并传入历史数据dataframe
m=Prophet()
m.fit(df)
future = m.make_future_dataframe(periods=365)
#future.head()
future.tail()
.dataframe thead tr:only-child th {
text-align: right;
}
.dataframe thead th {
text-align: left;
}
.dataframe tbody tr th {
vertical-align: top;
}
ds | |
---|---|
3265 | 2017-01-15 |
3266 | 2017-01-16 |
3267 | 2017-01-17 |
3268 | 2017-01-18 |
3269 | 2017-01-19 |
该predict方法将future的预测值分配每一行到yhat。如果你传入历史日期,它将提供样本内拟合,forecast对象是一个新的数据框,包含预测的列yhat,以及分量列和不确定性区间(指最大值最小值)。
forecast = m.predict(future) # 每次预测结果会有波动
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
.dataframe thead tr:only-child th {
text-align: right;
}
.dataframe thead th {
text-align: left;
}
.dataframe tbody tr th {
vertical-align: top;
}
ds | yhat | yhat_lower | yhat_upper | |
---|---|---|---|---|
3265 | 2017-01-15 | 8.210721 | 7.530825 | 8.943600 |
3266 | 2017-01-16 | 8.535794 | 7.831740 | 9.311551 |
3267 | 2017-01-17 | 8.323199 | 7.579130 | 9.125848 |
3268 | 2017-01-18 | 8.155820 | 7.410573 | 8.943443 |
3269 | 2017-01-19 | 8.167768 | 7.455376 | 8.931324 |
你可以通过调用该Prophet.plot方法并传递预测数据框来绘制预测。
m.plot(forecast);
如果你想查看预测的各个分量,可以使用Prophet.plot_componments方法。默认情况下,可以得到时间序列的趋势:年度季节性,每周季节性。如果你包含假期,它也将得到。
m.plot_components(forecast);
快速入门到这就结束了。主要讲了导入数据-拟合模型-待预测日期-预测方法-预测结果绘制-预测分量。