lstm python 代码实现降水预测
时间: 2023-10-14 17:05:49 浏览: 118
基于 LSTM 网络进行降雨径流预测附matlab代码.zip
5星 · 资源好评率100%
以下是一个基于LSTM的降水预测模型的Python代码实现示例:
首先,导入必要的库:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
```
接着,读取数据集并进行预处理:
```python
# 读取数据集
data = pd.read_csv('rainfall_data.csv')
# 按日期排序
data = data.sort_values('Date')
# 取出降水量列
rainfall = data['Rainfall'].values.reshape(-1, 1)
# 将数据集划分为训练集和测试集
train_size = int(len(rainfall) * 0.8)
test_size = len(rainfall) - train_size
train_data, test_data = rainfall[0:train_size,:], rainfall[train_size:len(rainfall),:]
# 归一化数据
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
# 将数据集转换为有监督学习问题
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 = 10
trainX, trainY = create_dataset(train_data, look_back)
testX, testY = create_dataset(test_data, look_back)
# 将数据集重塑为LSTM输入格式
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
```
然后,构建LSTM模型并进行训练:
```python
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
```
最后,使用训练好的模型进行预测并绘制预测结果:
```python
# 在训练集和测试集上进行预测
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))
# 绘制预测结果
trainPredictPlot = np.empty_like(rainfall)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
testPredictPlot = np.empty_like(rainfall)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(rainfall)-1, :] = testPredict
plt.plot(scaler.inverse_transform(rainfall))
plt.plot(trainPredictPlot)
plt.plot(testPredictPlot)
plt.show()
```
此代码实现了一个基于LSTM的降水预测模型,可以通过修改数据集、调整模型参数等进行进一步的改进。
阅读全文