1. 程式人生 > >PyTorch時間序列預測GPU執行示例模型

PyTorch時間序列預測GPU執行示例模型

官方Github上給的例子是CPU版本:https://github.com/pytorch/examples/tree/master/time_sequence_prediction

下面的程式碼將其改為了GPU版本。除了將網路模型和輸入遷移到顯示卡上之外,還有注意兩點:

一是計算隱藏層狀態和細胞狀態時也需要把h和c的值遷移到顯示卡上;

二是在畫圖之前需要把預測值遷移回到CPU上才能將其轉化為numpy陣列。

from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

class Sequence(nn.Module):
    def __init__(self):
        super(Sequence, self).__init__()
        self.lstm1 = nn.LSTMCell(1, 51)
        self.lstm2 = nn.LSTMCell(51, 51)
        self.linear = nn.Linear(51, 1)

    def forward(self, input, future = 0):
        outputs = []
        #h_t = torch.zeros(input.size(0), 51, dtype=torch.double)
        #c_t = torch.zeros(input.size(0), 51, dtype=torch.double)
        #h_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
        #c_t2 = torch.zeros(input.size(0), 51, dtype=torch.double)
        h_t = torch.zeros(input.size(0), 51, dtype=input.dtype, device=input.device)
        c_t = torch.zeros(input.size(0), 51, dtype=input.dtype, device=input.device)
        h_t2 = torch.zeros(input.size(0), 51, dtype=input.dtype, device=input.device)
        c_t2 = torch.zeros(input.size(0), 51, dtype=input.dtype, device=input.device)

        for i, input_t in enumerate(input.chunk(input.size(1), dim=1)):
            h_t, c_t = self.lstm1(input_t, (h_t, c_t))
            h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
            output = self.linear(h_t2)
            outputs += [output]
        for i in range(future):# if we should predict the future
            h_t, c_t = self.lstm1(output, (h_t, c_t))
            h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
            output = self.linear(h_t2)
            outputs += [output]
        outputs = torch.stack(outputs, 1).squeeze(2)
        return outputs


if __name__ == '__main__':
    # set random seed to 0
    np.random.seed(0)
    torch.manual_seed(0)
    # load data and make training set
    data = torch.load('traindata.pt')
    input = torch.from_numpy(data[3:, :-1])
    target = torch.from_numpy(data[3:, 1:])
    test_input = torch.from_numpy(data[:3, :-1])
    test_target = torch.from_numpy(data[:3, 1:])
    
    # move model to GPU
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print(device)
    
    input, target = input.to(device), target.to(device)
    test_input, test_target = test_input.to(device), test_target.to(device)
    
    # build the model
    seq = Sequence()
    seq.to(device)
    
    seq.double()
    criterion = nn.MSELoss()
    # use LBFGS as optimizer since we can load the whole data to train
    optimizer = optim.LBFGS(seq.parameters(), lr=0.8)
    
    epoch = 15
    #begin to train
    for i in range(epoch):
        print('STEP: ', i)
        
        def closure():
            optimizer.zero_grad()
            out = seq(input)
            #print('input size: ', input.size())
            loss = criterion(out, target)
            print('loss:', loss.item())
            loss.backward()
            return loss
    
        optimizer.step(closure)
        # begin to predict, no need to track gradient here
        with torch.no_grad():
            future = 1000
            pred = seq(test_input, future=future)
            loss = criterion(pred[:, :-future], test_target)
            print('test loss:', loss.item())
            #y = pred.detach().numpy()
            y = pred.detach().cpu().numpy()
        # draw the result
        plt.figure(figsize=(30,10))
        plt.title('Predict future values for time sequences\n(Dashlines are predicted values)', fontsize=30)
        plt.xlabel('x', fontsize=20)
        plt.ylabel('y', fontsize=20)
        plt.xticks(fontsize=20)
        plt.yticks(fontsize=20)
        def draw(yi, color):
            plt.plot(np.arange(input.size(1)), yi[:input.size(1)], color, linewidth = 2.0)
            plt.plot(np.arange(input.size(1), input.size(1) + future), yi[input.size(1):], color + ':', linewidth = 2.0)
        draw(y[0], 'r')
        draw(y[1], 'g')
        draw(y[2], 'b')
        plt.savefig('predict%d.pdf'%i)
        plt.close()

相關推薦

PyTorch時間序列預測GPU執行示例模型

官方Github上給的例子是CPU版本:https://github.com/pytorch/examples/tree/master/time_sequence_prediction下面的程式碼將其改為了GPU版本。除了將網路模型和輸入遷移到顯示卡上之外,還有注意兩點:一是

用python做時間序列預測九:ARIMA模型簡介

> 本篇介紹時間序列預測常用的ARIMA模型,通過了解本篇內容,將可以使用ARIMA預測一個時間序列。 ### 什麼是ARIMA? >- ARIMA是'Auto Regressive Integrated Moving Average'的簡稱。 >- ARIMA是一種基於時間序列歷史值和歷

8.4.2 時間序列預測——使用TFLearn自定義模型——程式碼執行錯誤及解決方法

《TensorFlow》:實戰Google深度學習框架中第八章的——8.4.2 時間序列預測——使用TFLearn自定義模型下的原始碼執行報錯: 原因分析: score=metrics.accuracy_score(y_test,y_predicted)該句程式碼中y_predi

使用Python為時間序列預測建立ARIMA模型

                     如何在Python中為時間序列預測建立ARIMA模型        ARIMA模型是一種流行且廣泛使用的

Pytorch LSTM 時間序列預測

詳情可以參見文章import torch import torch.nn as nn from torch.autograd import * import torch.optim as optim import torch.nn.functional as F import

prophet:時間序列預測模型原理

prophet:時間序列預測原理 介紹 prophet是Facebook 開源一款基於 Python 和 R 語言的資料預測工具即“先知”。Facebook 表示,Prophet 相比現有預測工具更加人性化,並且難得地提供 Python 和R的支援。它生

時間序列預測模型方法

簡介 時間序列預測法是一種歷史資料延伸預測,也稱歷史引伸預測法。是以時間數列所能反映的社會經濟現象的發展過程和規律性,進行引伸外推,預測其發展趨勢的方法。 時間序列,也叫時間數列、歷史複數或動態數列。

7天微課程day6——用ARIMA模型進行時間序列預測

宣告: 本文是系列課程的第6課 本文是對機器學習網站課程的翻譯 尊重原作者,尊重知識分享 用ARIMA模型進行時間序列預測 ARIMA(AutoRegressive Intergrated Moving Average)是一個非常非常流行的時間序列

Pytorch實現LSTM時間序列預測

摘要:本文主要基於Pytorch深度學習框架,實現LSTM神經網路模型,用於時間序列的預測。開發環境說明:Py

只需一行代碼!Python中9大時間序列預測模型

rim reg tsm 水平 包括 組成 相關性 sta mod 在時間序列問題上,機器學習被廣泛應用於分類和預測問題。當有預測模型來預測未知變量時,在時間充當獨立變量和目標因變量的情況下,時間序列預測就出現了。 預測值可以是潛在雇員的工資或銀行賬戶持有人的信用評分。任何正

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

keras-anomaly-detection 代碼分析——本質上就是SAE、LSTM時間序列預測

encoding urn odin forward mean code -a reat ati keras-anomaly-detection Anomaly detection implemented in Keras The source codes of the re

時間序列預測——深度好文

原文地址:https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-9-time-series-analysis-in-python-a270cb05e0b3 Open Machine Learnin

Tensorflow LSTM時間序列預測的嘗試

一、網上的資源 網上有不少用LSTM來預測時間序列的資源,如下面: 深度學習(08)_RNN-LSTM迴圈神經網路-03-Tensorflow進階實現 http://blog.csdn.net/u013082989/article/details/73693392 Applying

時間序列預測演算法總結

時間序列演算法 time series data mining 主要包括decompose(分析資料的各個成分,例如趨勢,週期性),prediction(預測未來的值),classification(對有序資料序列的feature提取與分類),clustering(相似數列聚類)等。 時間序

LSTM時間序列預測學習

一、檔案準備工作       下載好的例程式 二、開始執行   1、在程式所在目錄中(chapter_15)開啟終端   輸入下面的指令執行 python train_lstm.py 此時出現了報錯提

基於深度學習時間序列預測系統專案需求分析心得

專案第一次迭代已經進入了尾聲,在我們小組剛確定這個專案的時候,花了兩個周的時間來確定專案的需求。以下是我們在進行需求分析的一些心得。   需求分析過程:   (1) 小組內部進行討論:在進行團隊專案開發之初,我們在需求分析還有資料庫設計上花了很多時間,首先是進行多次需求分析的團隊會議,小組人員

ARIMA 時間序列預測

ARIMA 時間序列預測  (學習資料及程式碼均從網上獲取。) 資料記錄AirPassengers.csv: Month,#Passengers 1949-01,112 1949-02,118 1949-03,132 1949-04,129 1949-05,121 1949

Keras LSTM 時間序列預測

Keras LSTM 時間序列預測   international-airline-passengers.csv資料記錄: time,passengers "1949-01",112 "1949-02",118 "1949-03",132 "1949-04",129

基於Keras的LSTM多變數時間序列預測 (學習筆記)

本文翻譯自Jason Brownlee的部落格https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ 本部落格主要參考以下中文版部落格 https://blog.csdn.net/qq_280