LSTM预测径流python代码
时间: 2023-07-12 11:34:50 浏览: 152
以下是使用 LSTM 进行径流预测的 Python 代码:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
# 读取径流数据
data = pd.read_csv('runoff.csv', usecols=[1])
dataset = data.values
dataset = dataset.astype('float32')
# 数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# 划分训练集和测试集
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
# 将时间序列数据转换为监督学习数据
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 5
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# LSTM 模型
model = Sequential()
model.add(LSTM(64, input_shape=(look_back, 1)))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=32, verbose=2)
# 预测
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
# 反归一化
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
# 计算误差
trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:, 0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:, 0]))
print('Test Score: %.2f RMSE' % (testScore))
```
在上面的代码中,首先读取径流数据,然后使用 MinMaxScaler 进行数据归一化。接着,将时间序列数据转换为监督学习数据,其中 look_back 参数表示时间步长,即将 look_back 个时间步的数据作为输入,预测下一个时间步的径流数据。然后,定义 LSTM 模型,并训练模型。最后,使用模型进行预测,并计算预测误差。
阅读全文