1. 程式人生 > >Python時間序列LSTM預測系列學習筆記(1)-單變數

Python時間序列LSTM預測系列學習筆記(1)-單變數

本文是對:

https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/

https://blog.csdn.net/iyangdi/article/details/77853055

兩篇博文的學習筆記,兩個博主筆風都很浪,有些細節一筆帶過,本人以謙遜的態度進行了學習和整理,筆記內容都在程式碼的註釋中。有不清楚的可以去原博主穩重檢視。

資料集下載:https://datamarket.com/data/set/22r0/sales-of-shampoo-over-a-three-year-period

 

from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from math import sqrt
from matplotlib import pyplot
"""https://blog.csdn.net/iyangdi/article/details/77853055
    這個演算法並沒有什麼用,只是求了兩個陣列之間的標準差
    我們強行粗獷的把test陣列中第n-1個元素變成了預測陣列predictions中的第n個元素,作為測試結果來使用
    最後計算了了test陣列和predictions陣列之間的標準差,當做預測效果的評估
    所以第一節毫無意義"""

# 載入資料
def parser(x):
    return datetime.strptime(x, '%Y/%m/%d')


series = read_csv('data_set/shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True,
                  date_parser=parser)

# 分成訓練和測試集合,前24列給訓練集,後12行給測試集
X = series.values
train, test = X[0:-12], X[-12:]


#把陣列train賦值給一個history列表
history = [x for x in train]
#建立一個predictions列表,這個列表記錄了觀測值,建立一個predictions陣列中第n個元素,對應test陣列中第n-1個元素
predictions = list()
for i in range(len(test)):
    predictions.append(history[-1])  # history[-1],就是執行預測,這裡我們只是假設predictions陣列就是我們預測的結果
    history.append(test[i])  # 將新的測試資料加入模型

# 預測效果評估
rmse = sqrt(mean_squared_error(test, predictions))#返回的結果是測試陣列test,和觀測陣列predictions的標準差,https://www.cnblogs.com/nolonely/p/7009001.html
print('RMSE:%.3f' % rmse)

# 畫出預測+觀測值
pyplot.plot(test)#測試陣列
pyplot.plot(predictions)#觀測陣列
pyplot.show()