当前位置:   article > 正文

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

lstm python

原理:

递归神经网络RNN - 知乎

实验:

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

  1. import numpy as np
  2. def normalise_windows(window_data): # 数据全部除以最开始的数据再减一
  3. normalised_data = []
  4. for window in window_data:
  5. normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
  6. normalised_data.append(normalised_window)
  7. return normalised_data
  8. def load_data(filename, seq_len, normalise_window):
  9. f = open(filename, 'r').read() # 读取文件中的数据
  10. data = f.split('\n') # split() 方法用于把一个字符串分割成字符串数组,这里就是换行分割
  11. sequence_lenghth = seq_len + 1 # #得到长度为seq_len+1的向量,最后一个作为label
  12. result = []
  13. for index in range(len(data)-sequence_lenghth):
  14. result.append(data[index : index+sequence_lenghth]) # 制作数据集,从data里面分割数据
  15. if normalise_window:
  16. result = normalise_windows(result)
  17. result = np.array(result) # shape (4121,51) 4121代表行,51是seq_len+1
  18. row = round(0.9*result.shape[0]) # round() 方法返回浮点数x的四舍五入值
  19. train = result[:int(row), :] # 取前90%
  20. np.random.shuffle(train) # shuffle() 方法将序列的所有元素随机排序。
  21. x_train = train[:, :-1] # 取前50列,作为训练数据
  22. y_train = train[:, -1] # 取最后一列作为标签
  23. x_test = result[int(row):, :-1] # 取后10% 的前50列作为测试集
  24. y_test = result[int(row):, -1] # 取后10% 的最后一列作为标签
  25. x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) # 最后一个维度1代表一个数据的维度
  26. x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
  27. return [x_train, y_train, x_test, y_test]
  28. x_train, y_train, x_test, y_test = load_data('./sp500.csv', 50, True)
  29. print('shape_x_train',np.array(x_train).shape) #shape_x_train (3709, 50, 1)
  30. print('shape_y_train',np.array(y_train).shape) #shape_y_train (3709,)
  31. print('shape_x_test',np.array(x_test).shape) #shape_x_test (412, 50, 1)
  32. print('shape_y_test',np.array(y_test).shape) #shape_y_test (412,)

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

  1. import numpy as np
  2. from keras.layers.core import Dense, Activation, Dropout
  3. from keras.layers.recurrent import LSTM
  4. from keras.models import Sequential
  5. import time
  6. model = Sequential()
  7. model.add(LSTM(input_dim = 1, output_dim=50, return_sequences=True))
  8. model.add(Dropout(0.2))
  9. model.add(LSTM(100, return_sequences= False))
  10. model.add(Dropout(0.2))
  11. model.add(Dense(output_dim = 1))
  12. model.add(Activation('linear'))
  13. start = time.time()
  14. model.compile(loss='mse', optimizer='rmsprop')
  15. 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,)个维度的点,并于实际值比较画图:

  1. import warnings
  2. warnings.filterwarnings("ignore")
  3. def predict_point_by_point(model, data):
  4. predicted = model.predict(data) # 输入测试集的全部数据进行全部预测,(412,1)
  5. predicted = np.reshape(predicted, (predicted.size,))
  6. return predicted
  7. predictions = predict_point_by_point(model, x_test)
  8. import matplotlib.pylab as plt
  9. def plot_results(predicted_data, true_data):
  10. fig = plt.figure(facecolor='white')
  11. ax = fig.add_subplot(111)
  12. ax.plot(true_data, label='True Data')
  13. plt.plot(predicted_data, label='Prediction')
  14. plt.legend()
  15. plt.show()
  16. plot_results(predictions, y_test)

得出结果:

2.滚动预测:

  1. def predict_sequence_full(model, data, window_size):
  2. curr_frame = data[0] # (1, 50)
  3. predicted = []
  4. print('len(data)',len(data))
  5. for i in range(len(data)):
  6. predicted.append(model.predict(curr_frame[newaxis, :, :])[0, 0]) # 输入50个数据,预测出一个数据
  7. curr_frame = curr_frame[1:] # 取后面49个数据
  8. curr_frame = np.insert(curr_frame, [window_size - 1], predicted[-1], axis=0) # 将预测出的数据加在第50个数据点处
  9. return predicted
  10. predictions = predict_sequence_full(model, x_test, 50)
  11. import matplotlib.pylab as plt
  12. def plot_results(predicted_data, true_data):
  13. fig = plt.figure(facecolor='white')
  14. ax = fig.add_subplot(111)
  15. ax.plot(true_data, label='True Data')
  16. plt.plot(predicted_data, label='Prediction')
  17. plt.legend()
  18. plt.show()
  19. plot_results(predictions, y_test)

3.滑动窗口+滚动预测

  1. def predict_sequences_multiple(model, data, window_size, prediction_len):
  2. prediction_seqs = []
  3. for i in range(int(len(data) / prediction_len)): # 定滑动窗口的起始点
  4. curr_frame = data[i * prediction_len]
  5. predicted = []
  6. for j in range(prediction_len): # 与滑动窗口一样分析
  7. predicted.append(model.predict(curr_frame[newaxis, :, :])[0, 0])
  8. curr_frame = curr_frame[1:]
  9. curr_frame = np.insert(curr_frame, [window_size - 1], predicted[-1], axis=0)
  10. prediction_seqs.append(predicted)
  11. return prediction_seqs
  12. predictions = predict_sequences_multiple(model, x_test, 50, 50)
  13. import matplotlib.pylab as plt
  14. def plot_results_multiple(predicted_data, true_data, prediction_len):
  15. fig = plt.figure(facecolor='white')
  16. ax = fig.add_subplot(111)
  17. ax.plot(true_data, label='True Data')
  18. for i, data in enumerate(predicted_data):
  19. padding = [None for p in range(i * prediction_len)]
  20. plt.plot(padding + data, label='Prediction')
  21. plt.legend()
  22. plt.show()
  23. plot_results_multiple(predictions, y_test, 50)

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/631790
推荐阅读
相关标签
  

闽ICP备14008679号