lstm时间序列模型预测代码
七彩音符 深度学习在时间序列预测中具有很好的效果,其中LSTM(长短期记忆)模型是一种常用的深度学习模型。下面是LSTM时间序列模型预测的Python代码:
1.导入所需的库
```python
import numpy as np
import pandas as pd
dels import Sequential
from keras.layers import LSTM, Den
from sklearn.preprocessing import MinMaxScaler
```
2.读取数据
```python
data = pd.read_csv('data.csv', index_col=0)
```
3.数据预处理
栾川景区
```python
#将数据归一化,缩放到0-1之间
热爱生命的故事 scaler = MinMaxScaler(feature_range=(0, 1))
data_scaled = scaler.fit_transform(data)
#定义函数,将训练数据划分为X和y
def create_datat(datat, look_back=1):
X, y = [], []
for i in range(len(datat)-look_back):
X.append(datat[i:(i+look_back), 0])
y.append(datat[(i+look_back), 0])
党纪
return np.array(X), np.array(y)
#划分训练集和测试集
train_size = int(len(data_scaled) * 0.7)
test_size = len(data_scaled) - train_size
train, test = data_scaled[0:train_size,:], data_scaled[train_size:len(data_scaled),:]
look_back = 3 #每个样本包含的时间步数
X_train, y_train = create_datat(train, look_back)
X_test, y_test = create_datat(test, look_back)
#将数据reshape成LSTM需要的格式
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))
```
4.构建LSTM模型
```python
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 1)))
model.add(Den(1))
pile(loss='mean_squared_error', optimizer='adam')
就是这样
```
5.训练模型
```python
model.fit(X_train, y_train, epochs=100, batch_size=1, verbo=2)
```
6.模型预测
```python
常州恐龙园攻略 train_predict = model.predict(X_train)
公文通知
test_predict = model.predict(X_test)
#将预测结果转换为原始数据的比例
train_predict = scaler.inver_transform(train_predict)
y_train = scaler.inver_transform([y_train])
test_predict = scaler.inver_transform(test_predict)
y_test = scaler.inver_transform([y_test])
#计算训练集和测试集的误差
train_score = np.sqrt(mean_squared_error(y_train[0], train_predict[:,0]))
print('Train Score: %.2f RMSE' % (train_score))
家规 test_score = np.sqrt(mean_squared_error(y_test[0], test_predict[:,0]))
print('Test Score: %.2f RMSE' % (test_score))
```
以上就是LSTM时间序列模型预测的Python代码。通过以上代码,我们可以构建出一个LSTM模型,并对时间序列数据进行预测和评估。