用GRU算法实现风暴潮预测的代码python
时间: 2024-01-25 09:03:12 浏览: 118
以下是一个简单的使用GRU算法实现风暴潮预测的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, GRU
# 读取数据
data = pd.read_csv('storm_surge_data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
data['water_level'] = scaler.fit_transform(data['water_level'].values.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data.iloc[:train_size]
test_data = data.iloc[train_size:]
# 创建特征和标签
def create_dataset(dataset, look_back=1):
data_X, data_Y = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
data_X.append(a)
data_Y.append(dataset[i + look_back, 0])
return np.array(data_X), np.array(data_Y)
look_back = 10
train_X, train_Y = create_dataset(train_data.values, look_back)
test_X, test_Y = create_dataset(test_data.values, look_back)
# 转换为3D张量
train_X = np.reshape(train_X, (train_X.shape[0], train_X.shape[1], 1))
test_X = np.reshape(test_X, (test_X.shape[0], test_X.shape[1], 1))
# 创建模型
model = Sequential()
model.add(GRU(units=50, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=1, verbose=2)
# 测试模型
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)
# 反归一化
train_predict = scaler.inverse_transform(train_predict)
train_Y = scaler.inverse_transform([train_Y])
test_predict = scaler.inverse_transform(test_predict)
test_Y = scaler.inverse_transform([test_Y])
# 画图
plt.plot(train_data.index, train_data['water_level'], label='Train Data')
plt.plot(test_data.index, test_data['water_level'], label='Test Data')
plt.plot(train_data.index[look_back+1:], train_predict, label='Train Predictions')
plt.plot(test_data.index[look_back+1:], test_predict, label='Test Predictions')
plt.legend()
plt.show()
```
代码中使用了一个包含风暴潮数据的CSV文件。首先使用MinMaxScaler对数据进行归一化处理,然后将数据划分为训练集和测试集。接下来,将数据转换为特征和标签,创建一个3D张量,并使用GRU层和一个全连接层构建模型。最后,训练模型并使用反归一化将预测值转换回原始单位,最后画出预测结果。
阅读全文