时序算法lstm实测代码
程序员文章站
2024-03-14 11:33:10
...
时序算法lstm实测代码
说明
网上很多博客只给拟合数据图,本篇既有拟合数据也有预测数据。测试数据放入csv一列中即可。
直接上代码
import datetime
import numpy as np, matplotlib.pyplot as mp
from keras.models import Sequential
from keras.layers import Dense, LSTM
import numpy
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import pandas as pd
import numpy as np
import os
from keras.models import Sequential, load_model
from sklearn.preprocessing import MinMaxScaler
dataframe = pd.read_csv('C:\\Users\\lenovo\\Desktop\\1212\\usrdata2lst.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
# 将整型变为float
dataset = dataset.astype('float32')
#归一化 在下一步会讲解
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
train_size = int(len(dataset) * 1)
trainlist = dataset[:train_size]
# testlist = dataset[train_size:]
# 确定两个训练集:一个X的元素是数组,确定一个Y元素
def create_dataset(dataset, look_back):
#这里的look_back与timestep相同
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back)]
dataX.append(a)
dataY.append(dataset[i + look_back])
return numpy.array(dataX),numpy.array(dataY)
#向后看1440步预测一个数据
look_back = 1440
trainX,trainY = create_dataset(trainlist,look_back)
trainX = numpy.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
# 建模
model = Sequential()
model.add(LSTM(4, input_shape=(None,1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
#epochs越大越准确,但是越慢
model.fit(trainX, trainY, epochs=1, batch_size=1, verbose=2)
model.save(os.path.join("DATA","Test" + ".h5"))
# 预测未来1440个数据,本人数据16000多条
weilai_len=1440
for start in (0, 4000, 8000, 12000,trainX.shape[0]-1):
x_pred = np.linspace((start),
( start + weilai_len),
weilai_len, endpoint=False)
y_pred = [] # 存放预测序列
# 取到一个长度为前多少步的元素,
X_pred = trainX[start]
# 预测长度
for i in range(weilai_len):
# print(X_pred)
# 由训练的模型预测,得到一个预测值集Y_pred,第一个元素是预测值
Y_pred = model.predict(X_pred.reshape(-1, look_back, 1)) # 预测
# 放入一个结果
y_pred.append(Y_pred[0])
# 数组合并,舍弃旧的一个数据,留下旧数据和一个预测数据
X_pred = np.concatenate((X_pred, Y_pred))[1:] # 窗口滑动
# 预测序列反归一化
trainPredict = scaler.inverse_transform(y_pred)
mp.scatter(x_pred[0], trainPredict[0], c='r', s=9) # 预测起始点
mp.plot(x_pred, trainPredict, 'r') # 预测序列
# 原序列反归一化
trainY = scaler.inverse_transform(trainY)
plt.plot(trainY)
plt.show()
结果
大概这样,找不到原来的图片了,不好意思。
参考:
https://blog.csdn.net/qq_35649669/article/details/84990183
https://blog.csdn.net/qq_35649669/article/details/89575949
https://blog.csdn.net/Yellow_python/article/details/86668140?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://blog.csdn.net/qq_35649669/article/details/84990183
https://blog.csdn.net/qq_35649669/article/details/89575949
https://www.jianshu.com/p/38df71cad1f6
推荐阅读