1. 程式人生 > >python利用LSTM進行時間序列分析預測

python利用LSTM進行時間序列分析預測

  關鍵詞:python、Keras、LSTM、Time-Series-Prediction
  
  關於技術理論部分,可以參考這兩篇文章(RNNLSTM),本文主要從資料、程式碼角度,利用LSTM進行時間序列預測。

時間序列(或稱動態數列)是指將同一統計指標的數值按其發生的時間先後順序排列而成的數列。時間序列分析的主要目的是根據已有的歷史資料對未來進行預測。

時間序列構成要素:長期趨勢,季節變動,迴圈變動,不規則變動

  • 長期趨勢( T )現象在較長時期內受某種根本性因素作用而形成的總的變動趨勢
  • 季節變動( S )現象在一年內隨著季節的變化而發生的有規律的週期性變動
  • 迴圈變動( C )現象以若干年為週期所呈現出的波浪起伏形態的有規律的變動
  • 不規則變動(I )是一種無規律可循的變動,包括嚴格的隨機變動和不規則的突發性影響很大的變動兩種型別

(1)原始時間序列資料(只列出了18行)

1455.219971
1399.420044
1402.109985
1403.449951
1441.469971
1457.599976
1438.560059
1432.25
1449.680054
1465.150024
1455.140015
1455.900024
1445.569946
1441.359985
1401.530029
1410.030029
1404.089966
1398.560059

(2)處理資料使之符合LSTM的要求

為了更加直觀的瞭解資料格式,程式碼中加入了一些列印(print),並且後面加了註釋,就是輸出值

def load_data(filename, seq_len):
    f = open(filename, 'rb').read()
    data = f.split('\n')

    print('data len:',len(data))       #4172
    print('sequence len:',seq_len)     #50

    sequence_length = seq_len + 1
    result = []
    for index in range(len(data) - sequence_length):
        result.append(data[index: index + sequence_length])  #得到長度為seq_len+1的向量,最後一個作為label
print('result len:',len(result)) #4121 print('result shape:',np.array(result).shape) #(4121,51) result = np.array(result) #劃分train、test row = round(0.9 * result.shape[0]) train = result[:row, :] np.random.shuffle(train) x_train = train[:, :-1] y_train = train[:, -1] x_test = result[row:, :-1] y_test = result[row:, -1] x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) print('X_train shape:',X_train.shape) #(3709L, 50L, 1L) print('y_train shape:',y_train.shape) #(3709L,) print('X_test shape:',X_test.shape) #(412L, 50L, 1L) print('y_test shape:',y_test.shape) #(412L,) return [x_train, y_train, x_test, y_test]

(3)LSTM模型

本文使用的是keras深度學習框架,讀者可能用的是其他的,諸如theano、tensorflow等,大同小異。

LSTM的結構可以自己定製,Stack LSTM or Bidirectional LSTM

def build_model(layers):  #layers [1,50,100,1]
    model = Sequential()

    #Stack LSTM
    model.add(LSTM(input_dim=layers[0],output_dim=layers[1],return_sequences=True))
    model.add(Dropout(0.2))

    model.add(LSTM(layers[2],return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Dense(output_dim=layers[3]))
    model.add(Activation("linear"))

    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("Compilation Time : ", time.time() - start)
    return model

(4)LSTM訓練預測

1.直接預測

def predict_point_by_point(model, data):
    predicted = model.predict(data)
    print('predicted shape:',np.array(predicted).shape)  #(412L,1L)
    predicted = np.reshape(predicted, (predicted.size,))
    return predicted

2.滾動預測

def predict_sequence_full(model, data, window_size):  #data X_test
    curr_frame = data[0]  #(50L,1L)
    predicted = []
    for i in xrange(len(data)):
        #x = np.array([[[1],[2],[3]], [[4],[5],[6]]])  x.shape (2, 3, 1) x[0,0] = array([1])  x[:,np.newaxis,:,:].shape  (2, 1, 3, 1)
        predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])  #np.array(curr_frame[newaxis,:,:]).shape (1L,50L,1L)
        curr_frame = curr_frame[1:]
        curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)   #numpy.insert(arr, obj, values, axis=None)
    return predicted

2.滑動視窗+滾動預測

def predict_sequences_multiple(model, data, window_size, prediction_len):  #window_size = seq_len
    prediction_seqs = []
    for i in xrange(len(data)/prediction_len):
        curr_frame = data[i*prediction_len]
        predicted = []
        for j in xrange(prediction_len):
            predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
            curr_frame = curr_frame[1:]
            curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
        prediction_seqs.append(predicted)
    return prediction_seqs

(5)完整程式碼

# -*- coding: utf-8 -*-

from __future__ import print_function

import time
import warnings
import numpy as np
import time
import matplotlib.pyplot as plt
from numpy import newaxis
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

warnings.filterwarnings("ignore")

def load_data(filename, seq_len, normalise_window):
    f = open(filename, 'rb').read()
    data = f.split('\n')

    print('data len:',len(data))
    print('sequence len:',seq_len)

    sequence_length = seq_len + 1
    result = []
    for index in range(len(data) - sequence_length):
        result.append(data[index: index + sequence_length])  #得到長度為seq_len+1的向量,最後一個作為label

    print('result len:',len(result))
    print('result shape:',np.array(result).shape)
    print(result[:1])

    if normalise_window:
        result = normalise_windows(result)

    print(result[:1])
    print('normalise_windows result shape:',np.array(result).shape)

    result = np.array(result)

    #劃分train、test
    row = round(0.9 * result.shape[0])
    train = result[:row, :]
    np.random.shuffle(train)
    x_train = train[:, :-1]
    y_train = train[:, -1]
    x_test = result[row:, :-1]
    y_test = result[row:, -1]

    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    return [x_train, y_train, x_test, y_test]

def normalise_windows(window_data):
    normalised_data = []
    for window in window_data:   #window shape (sequence_length L ,)  即(51L,)
        normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
        normalised_data.append(normalised_window)
    return normalised_data

def build_model(layers):  #layers [1,50,100,1]
    model = Sequential()

    model.add(LSTM(input_dim=layers[0],output_dim=layers[1],return_sequences=True))
    model.add(Dropout(0.2))

    model.add(LSTM(layers[2],return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Dense(output_dim=layers[3]))
    model.add(Activation("linear"))

    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("Compilation Time : ", time.time() - start)
    return model

#直接全部預測
def predict_point_by_point(model, data):
    predicted = model.predict(data)
    print('predicted shape:',np.array(predicted).shape)  #(412L,1L)
    predicted = np.reshape(predicted, (predicted.size,))
    return predicted

#滾動預測
def predict_sequence_full(model, data, window_size):  #data X_test
    curr_frame = data[0]  #(50L,1L)
    predicted = []
    for i in xrange(len(data)):
        #x = np.array([[[1],[2],[3]], [[4],[5],[6]]])  x.shape (2, 3, 1) x[0,0] = array([1])  x[:,np.newaxis,:,:].shape  (2, 1, 3, 1)
        predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])  #np.array(curr_frame[newaxis,:,:]).shape (1L,50L,1L)
        curr_frame = curr_frame[1:]
        curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)   #numpy.insert(arr, obj, values, axis=None)
    return predicted

def predict_sequences_multiple(model, data, window_size, prediction_len):  #window_size = seq_len
    prediction_seqs = []
    for i in xrange(len(data)/prediction_len):
        curr_frame = data[i*prediction_len]
        predicted = []
        for j in xrange(prediction_len):
            predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
            curr_frame = curr_frame[1:]
            curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
        prediction_seqs.append(predicted)
    return prediction_seqs

def plot_results(predicted_data, true_data, filename):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    plt.plot(predicted_data, label='Prediction')
    plt.legend()
    plt.show()
    plt.savefig(filename+'.png')

def plot_results_multiple(predicted_data, true_data, prediction_len):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    #Pad the list of predictions to shift it in the graph to it's correct start
    for i, data in enumerate(predicted_data):
        padding = [None for p in xrange(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()
    plt.savefig('plot_results_multiple.png')

if __name__=='__main__':
    global_start_time = time.time()
    epochs  = 1
    seq_len = 50

    print('> Loading data... ')

    X_train, y_train, X_test, y_test = load_data('sp500.csv', seq_len, True)

    print('X_train shape:',X_train.shape)  #(3709L, 50L, 1L)
    print('y_train shape:',y_train.shape)  #(3709L,)
    print('X_test shape:',X_test.shape)    #(412L, 50L, 1L)
    print('y_test shape:',y_test.shape)    #(412L,)

    print('> Data Loaded. Compiling...')

    model = build_model([1, 50, 100, 1])

    model.fit(X_train,y_train,batch_size=512,nb_epoch=epochs,validation_split=0.05)

    multiple_predictions = predict_sequences_multiple(model, X_test, seq_len, prediction_len=50)
    print('multiple_predictions shape:',np.array(multiple_predictions).shape)   #(8L,50L)

    full_predictions = predict_sequence_full(model, X_test, seq_len)
    print('full_predictions shape:',np.array(full_predictions).shape)    #(412L,)

    point_by_point_predictions = predict_point_by_point(model, X_test)
    print('point_by_point_predictions shape:',np.array(point_by_point_predictions).shape)  #(412L)

    print('Training duration (s) : ', time.time() - global_start_time)

    plot_results_multiple(multiple_predictions, y_test, 50)
    plot_results(full_predictions,y_test,'full_predictions')
    plot_results(point_by_point_predictions,y_test,'point_by_point_predictions')

相關推薦

python利用LSTM進行時間序列分析預測

  關鍵詞:python、Keras、LSTM、Time-Series-Prediction      關於技術理論部分,可以參考這兩篇文章(RNN、LSTM),本文主要從資料、程式碼角度,利用LSTM進行時間序列預測。 時間序列(或稱動態數列)是指

乾貨|python利用LSTM進行時間序列分析預測

時間序列(或稱動態數列)是指將同一統計指標的數值按其發生的時間先後順序排列而成的數列。時間序列分析的主要目的是根據已有的歷史資料對未來進行預測。時間序列構成要素:長期趨勢,季節變動,迴圈變動,不規則變動長期趨勢( T )現象在較長時期內受某種根本性因素作用而形成的總的變動趨勢

利用ARIMA進行時間序列資料分析Python

0 導讀 閱讀本文需要有掌握基本的ARIMA知識,倘若ARIMA相關內容已經遺忘,此處提供以下博文幫你回憶一下: 本文主要分為四個部分:  用pandas處理時序資料 檢驗序資料的穩定性 處理時序資料變成穩定資料 時序資料的預測 和許多時間序列分析一樣,本文同樣使

基於R語言的簡單時間序列分析預測

資料來源: R語言自帶 co2 資料集 分析工具:R-3.5.0 & Rstudio-1.1.453 本篇分析只是一個簡單的教程,不作深究 #清理環境,載入包 rm(list=ls()) library(forecast) library(tseries) #檢視資料 co2 Vi

python利用time進行時間時間戳之間的相互轉換

Note:原文:https://blog.csdn.net/lykio_881210/article/details/79422531 標準時間向時間戳轉換: 1、獲取標準時間 2、使用strptime()轉換成時間陣列 3、使用mktime()轉換成時間戳 時間戳轉換成

ARIMA時間序列分析-----Python例項(一週銷售營業額預測

以ARIMA模型為例介紹時間序列演算法在python中是如何實現的,一下是應用Python語言建模步驟: -- coding: utf-8 -- “”” Created on Mon Apr 2 16:45:36 2018 @author: hou

利用python做資料分析》第十章:時間序列分析

import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline //anaconda/lib/python2.7/site-packa

86、使用Tensorflow實現,LSTM時間序列預測預測正弦函數

ati pre win real testing could sqrt sha ima ‘‘‘ Created on 2017年5月21日 @author: weizhen ‘‘‘ # 以下程序為預測離散化之後的sin函數 import numpy as np impo

Python時間序列分析

單獨 自己 line pandas mage lse atp 刻度 sta Pandas生成時間序列: import pandas as pd import numpy as np   時間序列 時間戳(timestamp) 固定周期(period) 時間間隔(int

Keras之MLPR:利用MLPR演算法(3to1【視窗法】+【Input(3)→(12+8)(relu)→O(mse)】)實現根據歷史航空旅客數量資料集(時間序列資料)預測下月乘客數量問題

Keras之MLPR:利用MLPR演算法(3to1【視窗法】+【Input(3)→(12+8)(relu)→O(mse)】)實現根據歷史航空旅客數量資料集(時間序列資料)預測下月乘客數量問題   輸出結果   設計思路  

Keras之MLPR:利用MLPR演算法(1to1+【Input(1)→8(relu)→O(mse)】)實現根據歷史航空旅客數量資料集(時間序列資料)預測下月乘客數量問題

Keras之MLPR:利用MLPR演算法(1to1+【Input(1)→8(relu)→O(mse)】)實現根據歷史航空旅客數量資料集(時間序列資料)預測下月乘客數量問題 輸出結果 單位為:千人   設計思路   實現程式碼

【統計學】【2017.05】時間序列資料預測分析

本文為布拉格捷克理工大學(作者:Oleg Ostashchuk)的碩士論文,共78頁。 本文討論了時間序列分析和預測的問題。論文的目的是研究現有的時間序列預測方法,包括必要的資料預處理步驟。本文選取了ARIMA、人工神經網路和雙指數平滑三種有前景的預測方法。本文的主要工作是對所提供的資

SVR,時間序列分析的評價指標,python資料標準化

知識點 SVR 參考 支援向量機(SVM)是一種分類演算法,但是也可以做迴歸,根據輸入的資料不同可做不同的模型(若輸入標籤為連續值則做迴歸,若輸入標籤為分類值則用SVC做分類) 對於SVM演算法,我們首先匯入sklearn.svm中的

時間序列分析預測

導論 研究時間序列主要目的:進行預測,根據已有的時間序列資料預測未來的變化。 時間序列預測關鍵:確定已有的時間序列的變化模式,並假定這種模式會延續到未來。 時間序列預測法的基本特點 假設事物發展趨勢會延伸到未來 預測所依據的資料具有不規則性 不

使用R語言進行時間序列(arima,指數平滑)分析

讀時間序列資料 您要分析時間序列資料的第一件事就是將其讀入R,並繪製時間序列。您可以使用scan()函式將資料讀入R,該函式假定連續時間點的資料位於包含一列的簡單文字檔案中。   資料集如下所示: Age of Death of Successive Kings of England#sta

【原始碼】時間序列分析預測工具箱(Time Series Analysis and Forecast,TSAF)

時間序列是一組隨時間變化而收集的定量型變數觀測值。比如:道瓊斯工業股價指數、線上銷售、庫存、客戶數量、利率、費用等歷史資料都屬於時間序列。 預測時間序列變數對於企業準確掌控運營狀態非常有用。通常,獨立變數不能用來建立時間序列變數的迴歸模型。 時間序列分析的特點:

python時間序列分析(ARIMA模型)

原文地址:https://blog.csdn.net/u011596455/article/details/78650458 轉載請註明出處。 什麼是時間序列       時間序列簡單的說就是各時間點上形成的數值序列,時間序列分析就是通過觀察歷史資料預測未來的值。在這裡需要

[TensorFlow深度學習入門]實戰十·用RNN(LSTM)做時間序列預測(曲線擬合)

[TensorFlow深度學習入門]實戰十·用RNN(LSTM)做時間序列預測(曲線擬合) %matplotlib inline import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" import numpy as np import

LSTM時間序列預測的思路,tensorflow程式碼實現及傳入資料格式

首先推薦一個對LSTM一些類函式進行說明的部落格: 函式說明 我的目標是用LSTM進行某種水果價格的預測,一開始我的做法是,將一種水果前n天的價格作為變數傳入,即這樣傳入的DataFrame格式是有n+1列,結果訓練出來的效果不盡人意,完全比不上之前我用ARIMA時間序列去擬合價格曲線

python資料分析時間序列分析(Time series analysis)

何為時間序列分析: 時間序列經常通過折線圖繪製。時間序列用於統計,訊號處理,模式識別,計量經濟學,數學金融,天氣預報,地震預測,腦電圖,控制工程,天文學,通訊工程,以及主要涉及時間測量的任何應用科學和工程領域。 時間序列分析包括用於分析時間序列資料的方法,以便提取有意義的統計資料