小学期09

实验名称

时间序列分析应用练习

实验目的

  1. 熟悉Pandas的一些基本操作及数据样本的可视化分析;
  2. 掌握如何使用Prophet建立时间序列模型;
  3. 掌握计算预测值和真实值的MAPE和MSE值的方法;
  4. 掌握使用 Dickey-Fuller 测试来验证序列的平稳性。

实验背景

本次作业我们选用维基百科 Machine Learning 页面每日浏览量统计数据

实验原理

时间序列分析使用的自回归移动平均模型(ARMA(p,q))是时间序列中最为重要的模型之一,它主要由两 部分组成: AR代表p阶自回归过程,MA代表q阶移动平均过程,:

实验步骤

准备环境

打开终端,安装statsmodels

pip install statsmodels==0.11.0
pip install pystan
conda install -c conda-forge fbprophet
pip install plotly
pip install fbprophet

准备数据

1、打开丘比特笔记本
2、导入实验所需要的资源库

import warnings 
import numpy as np 
import pandas as pd 
import os 
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
from plotly import graph_objs as go 
import requests 
import pandas as pd

3、环境设置,初始化ploty绘图模式,并忽略告警

init_notebook_mode(connected=True) 
warnings.filterwarnings('ignore')
    <script type="text/javascript">
    window.PlotlyConfig = {MathJaxConfig: 'local'};
    if (window.MathJax) {MathJax.Hub.Config({SVG: {font: "STIX-Web"}});}
    if (typeof require !== 'undefined') {
    require.undef("plotly");
    requirejs.config({
        paths: {
            'plotly': ['https://cdn.plot.ly/plotly-latest.min']
        }
    });
    require(['plotly'], function(Plotly) {
        window._Plotly = Plotly;
    });
    }
    </script>

4、读取并加载浏览量统计数据集

df = pd.read_csv('wiki_machine_learning1.csv', sep=' ') # 过滤没浏览量的记录 
df = df[df['count'] != 0] 
df.head()
datecountlangpagerankmonthtitle
812015-01-011414enMachine_learning8708201501Machine_learning
802015-01-021920enMachine_learning8708201501Machine_learning
792015-01-031338enMachine_learning8708201501Machine_learning
782015-01-041404enMachine_learning8708201501Machine_learning
772015-01-052264enMachine_learning8708201501Machine_learning

5、查看数据总量

df.shape
(383, 7)

Prophet建模预测

6、将原数据中的时间字符串处理成日期格式

df.date = pd.to_datetime(df.date) 
df.head()
datecountlangpagerankmonthtitle
812015-01-011414enMachine_learning8708201501Machine_learning
802015-01-021920enMachine_learning8708201501Machine_learning
792015-01-031338enMachine_learning8708201501Machine_learning
782015-01-041404enMachine_learning8708201501Machine_learning
772015-01-052264enMachine_learning8708201501Machine_learning

7、查看数据集后5行

df.tail()
datecountlangpagerankmonthtitle
3822016-01-161644enMachine_learning8708201601Machine_learning
3812016-01-171836enMachine_learning8708201601Machine_learning
3762016-01-182983enMachine_learning8708201601Machine_learning
3752016-01-193389enMachine_learning8708201601Machine_learning
3722016-01-203559enMachine_learning8708201601Machine_learning

8、接下来,使用 plotly 提供的方法定义一个 plotly_df 函数,以方便绘制出可交互式图像。

def plotly_df(df, title=''):     data = []     for column in df.columns:         #使用plotly绘制折线图         trace = go.Scatter(x=df.index, y=df[column], mode='lines', name=column)         #添加到data        data.append(trace)    #设置标题     layout = dict(title=title)     fig = dict(data=data, layout=layout)     #绘图 i    plot(fig, show_link=False)

9、然后,利用定义好的绘图函数,绘制数据集浏览量随时间的变化情况。

plotly_df(df.set_index('date')[['count']])

在这里插入图片描述

10、接下来使用 Prophet 预测时间序列数据。首先将 DataFrame 处理成 Prophet 支持的格式。

#取出日期和访问量 df = df[['date', 'count']] #重命名列名 df.columns = ['ds', 'y'] df.tail()
dsy
3822016-01-161644
3812016-01-171836
3762016-01-182983
3752016-01-193389
3722016-01-203559

11、然后,将原始数据后 30 条切分用于预测,只使用 30 条之前的历史数据进行建模。

predictions = 30 #取到倒数30条 train_df = df[:-predictions].copy() train_df.tail()
dsy
3582015-12-172870
3632015-12-182475
3642015-12-191659
3442015-12-201534
3432015-12-212425

12、使用 Prophet 对 train_df 数据建模,预测后 30 天的结果,并输出 1 月 20 日当天的预测结果。

from fbprophet import Prophet#创建Prophet对象m = Prophet()#填充训练数据,生成模型m.fit(train_df)#预测后三十天的访问量future = m.make_future_dataframe(periods=predictions)forecast = m.predict(future)forecast.tail()
INFO:fbprophet:Disabling yearly seasonality. Run prophet with yearly_seasonality=True to override this.INFO:fbprophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
dstrendyhat_loweryhat_uppertrend_lowertrend_upperadditive_termsadditive_terms_loweradditive_terms_upperweeklyweekly_lowerweekly_uppermultiplicative_termsmultiplicative_terms_lowermultiplicative_terms_upperyhat
3782016-01-162971.1254401693.0203642505.0844572950.5726212992.357064-861.666255-861.666255-861.666255-861.666255-861.666255-861.6662550.00.00.02109.459185
3792016-01-172976.4235761863.3996042682.6831192954.8661422999.140416-720.685978-720.685978-720.685978-720.685978-720.685978-720.6859780.00.00.02255.737598
3802016-01-182981.7217132859.4647913672.1686532958.8933713006.114622281.426215281.426215281.426215281.426215281.426215281.4262150.00.00.03263.147928
3812016-01-192987.0198493150.0608663931.1557352962.5771623012.714353541.366440541.366440541.366440541.366440541.366440541.3664400.00.00.03528.386289
3822016-01-202992.3179863020.3165573836.6134092966.9836833019.515352425.464520425.464520425.464520425.464520425.464520425.4645200.00.00.03417.782506
#拼接DataFrame,方便使用真实值和预测值进行计算cmp_df = forecast.set_index('ds')[['yhat', 'yhat_lower', 'yhat_upper']].join(df.set_index('ds'))cmp_df.head()#计算MAEcmp_df['e'] = cmp_df['y'] - cmp_df['yhat']#计算MAPEcmp_df['p'] = 100 * cmp_df['e'] / cmp_df['y']print('MAPE = ', round(np.mean(abs(cmp_df[-predictions:]['p'])), 2))print('MAE = ', round(np.mean(abs(cmp_df[-predictions:]['e'])), 2))
MAPE =  34.19MAE =  593.37
import statsmodels.api as smfrom scipy import statsimport matplotlib.pyplot as plt%matplotlib inline#设置图表结构plt.rcParams['figure.figsize'] = (15, 10)
sm.tsa.seasonal_decompose(train_df['y'].values, freq=7).plot()print("Dickey-Fuller test: p=%f" % sm.tsa.stattools.adfuller(train_df['y'])[1])
Dickey-Fuller test: p=0.107392

在这里插入图片描述

实验总结

通过本次作业,练习Pandas的一些基本操作及数据样本的可视化分析,并学会使用Prophet建立时间序 列模型,进行预测,在这个基础上,理解掌握简单的评价指标MAPE和MAE。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值