基于LSTM的时间序列预测-原理-python代码详解

原理:

递归神经网络RNN - 知乎

实验:

首先我们需要下载数据,之后我们对数据进行相应的处理,取前90%作为训练集,10%作为测试集。

import numpy as np
def normalise_windows(window_data): # 数据全部除以最开始的数据再减一
    normalised_data = []
    for window in window_data:
        normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
        normalised_data.append(normalised_window)
    return normalised_data

def load_data(filename, seq_len, normalise_window):
    f = open(filename, 'r').read() # 读取文件中的数据
    data = f.split('\n') # split() 方法用于把一个字符串分割成字符串数组,这里就是换行分割
    sequence_lenghth = seq_len + 1 # #得到长度为seq_len+1的向量,最后一个作为label
    result = []
    for index in range(len(data)-sequence_lenghth):
        result.append(data[index : index+sequence_lenghth]) # 制作数据集,从data里面分割数据
    if normalise_window:
        result = normalise_windows(result)
    result = np.array(result) # shape (4121,51) 4121代表行,51是seq_len+1
    row = round(0.9*result.shape[0]) # round() 方法返回浮点数x的四舍五入值
    train = result[:int(row), :] # 取前90%
    np.random.shuffle(train) # shuffle() 方法将序列的所有元素随机排序。
    x_train = train[:, :-1] # 取前50列,作为训练数据
    y_train = train[:, -1]  # 取最后一列作为标签
    x_test = result[int(row):, :-1] # 取后10% 的前50列作为测试集
    y_test = result[int(row):, -1] # 取后10% 的最后一列作为标签
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 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]

x_train, y_train, x_test, y_test = load_data('./sp500.csv', 50, True)
print('shape_x_train',np.array(x_train).shape) #shape_x_train (3709, 50, 1)
print('shape_y_train',np.array(y_train).shape) #shape_y_train (3709,)
print('shape_x_test',np.array(x_test).shape) #shape_x_test (412, 50, 1)
print('shape_y_test',np.array(y_test).shape) #shape_y_test (412,)

数据有了之后我们开始建立神经网络模型:

import numpy as np
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
import time
model = Sequential()
model.add(LSTM(input_dim = 1, output_dim=50, return_sequences=True)) 
model.add(Dropout(0.2))
model.add(LSTM(100, return_sequences= False))
model.add(Dropout(0.2))
model.add(Dense(output_dim = 1))
model.add(Activation('linear'))
start = time.time()
model.compile(loss='mse', optimizer='rmsprop')
print ('compilation time : ', time.time() - start)

建立模型之后就开始将数据传入,并进行训练:

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

这里我们总结一下这个模型,这个模型按照上述参数的定义,模型的输入是前50个数据,输出接下来的一个数据。接下来我们就可以按照不同的方式进行预测:

1.点到点的直接预测,输入测试集(412,50)的维度的点,预测(412,)个维度的点,并于实际值比较画图:

import warnings
warnings.filterwarnings("ignore")
def predict_point_by_point(model, data):
    predicted = model.predict(data) # 输入测试集的全部数据进行全部预测,(412,1)
    predicted = np.reshape(predicted, (predicted.size,)) 
    return predicted
predictions = predict_point_by_point(model, x_test)

import matplotlib.pylab as plt
def plot_results(predicted_data, true_data):
    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()
plot_results(predictions, y_test)

得出结果:

2.滚动预测:

def predict_sequence_full(model, data, window_size):
    curr_frame = data[0] # (1, 50)
    predicted = []
    print('len(data)',len(data))
    for i in range(len(data)):
        predicted.append(model.predict(curr_frame[newaxis, :, :])[0, 0]) # 输入50个数据,预测出一个数据
        curr_frame = curr_frame[1:] # 取后面49个数据
        curr_frame = np.insert(curr_frame, [window_size - 1], predicted[-1], axis=0) # 将预测出的数据加在第50个数据点处
    return predicted
predictions = predict_sequence_full(model, x_test, 50)

import matplotlib.pylab as plt
def plot_results(predicted_data, true_data):
    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()
plot_results(predictions, y_test)

3.滑动窗口+滚动预测

def predict_sequences_multiple(model, data, window_size, prediction_len):
    prediction_seqs = []
    for i in range(int(len(data) / prediction_len)): # 定滑动窗口的起始点
        curr_frame = data[i * prediction_len]
        predicted = []
        for j in range(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
predictions = predict_sequences_multiple(model, x_test, 50, 50)

import matplotlib.pylab as plt
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')
    for i, data in enumerate(predicted_data):
        padding = [None for p in range(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()
plot_results_multiple(predictions, y_test, 50)

github链接:https://github.com/ZhiqiangHo/code-of-csdn/tree/master/time_series_prediction/LSTM

【为什么要学习这门课程】深度学习框架如TensorFlow和Pytorch掩盖了深度学习底层实现方法,那能否能用Python代码从零实现来学习深度学习原理呢?本课程就为大家提供了这个可能,有助于深刻理解深度学习原理。左手原理、右手代码,双管齐下!本课程详细讲解深度学习原理并进行Python代码实现深度学习网络。课程内容涵盖感知机、多层感知机、卷积神经网络、循环神经网络,并使用Python 3及Numpy、Matplotlib从零实现上述神经网络。本课程还讲述了神经网络的训练方法与实践技巧,且开展了代码实践演示。课程对于核心内容讲解深入细致,如基于计算图理解反向传播算法,并用数学公式推导反向传播算法;另外还讲述了卷积加速方法im2col。【课程收获】本课程力求使学员通过深度学习原理、算法公式及Python代码的对照学习,摆脱框架而掌握深度学习底层实现原理与方法。本课程将给学员分享深度学习的Python实现代码。课程代码通过Jupyter Notebook演示,可在Windows、ubuntu等系统上运行,且不需GPU支持。【优惠说明】 课程正在优惠中!  备注:购课后可加入白勇老师课程学习交流QQ群:957519975【相关课程】学习本课程的前提是会使用Python语言以及Numpy和Matplotlib库。相关课程链接如下:《Python编程的术与道:Python语言入门》https://edu.csdn.net/course/detail/27845《玩转Numpy计算库》https://edu.csdn.net/lecturer/board/28656《玩转Matplotlib数据绘图库》https://edu.csdn.net/lecturer/board/28720【课程内容导图及特色】
LSTM是一种常用于时间序列预测的深度学习模型,可以通过Python来实现。以下是一个简单的LSTM时间序列预测Python示例: 首先,需要导入所需的库:numpy、pandas、matplotlib和tensorflow。 ``` python import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM ``` 接下来,可以读取数据集,对其进行预处理,并将其分为训练集和测试集。 ``` python # 读取数据集 data = pd.read_csv('data.csv', parse_dates=['date'], index_col='date') # 数据预处理 data = data.resample('D').sum() data = data.fillna(method='ffill') # 将数据集分为训练集和测试集 train_data = data[:'2021'] test_data = data['2022':] ``` 然后,需要将数据转换为模型可以处理的格式,这里使用时间窗口方法来转换数据。 ``` python # 时间窗口函数 def create_time_windows(data, window_size): X = [] y = [] for i in range(len(data)-window_size): X.append(data[i:i+window_size]) y.append(data[i+window_size]) return np.array(X), np.array(y) # 创建时间窗口 window_size = 7 X_train, y_train = create_time_windows(train_data.values, window_size) X_test, y_test = create_time_windows(test_data.values, window_size) ``` 接下来,需要构建LSTM模型,并进行训练和预测。 ``` python # 构建LSTM模型 model = Sequential() model.add(LSTM(64, input_shape=(window_size, 1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') # 训练模型 model.fit(X_train, y_train, epochs=100, batch_size=16) # 进行预测 train_predict = model.predict(X_train) test_predict = model.predict(X_test) ``` 最后,可以绘制训练集和测试集的真实值和预测值,以及模型的损失曲线。 ``` python # 绘制真实值和预测值 plt.plot(train_data.index[window_size:], train_data.values[window_size:]) plt.plot(train_data.index[window_size:], train_predict) plt.plot(test_data.index[window_size:], test_data.values[window_size:]) plt.plot(test_data.index[window_size:], test_predict) plt.legend(['train', 'train predict', 'test', 'test predict']) plt.show() # 绘制损失曲线 plt.plot(model.history.history['loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.show() ``` 以上是一个简单的LSTM时间序列预测Python示例。当然,在实际应用中,需要根据具体问题进行调整和优化。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值