写一个用lstm模型预测风电功率的代码
时间: 2024-03-13 08:46:02 浏览: 86
好的,这是一个简单的用LSTM模型预测风电功率的代码(仅供参考):
```python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载数据
data = pd.read_csv('wind_power.csv')
# 将数据集拆分为训练集和测试集
train_set = data.iloc[:800, 1:2].values
test_set = data.iloc[800:, 1:2].values
# 数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
train_set_scaled = scaler.fit_transform(train_set)
# 创建训练集
X_train = []
y_train = []
for i in range(60, 800):
X_train.append(train_set_scaled[i - 60:i, 0])
y_train.append(train_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
# 将训练数据集重塑为LSTM输入格式
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(X_train, y_train, epochs=50, batch_size=32)
# 创建测试集
inputs = data.iloc[len(data) - len(test_set) - 60:, 1:2].values
inputs = scaler.transform(inputs)
X_test = []
for i in range(60, 200):
X_test.append(inputs[i - 60:i, 0])
X_test = np.array(X_test)
# 将测试集重塑为LSTM输入格式
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# 预测测试集
predicted_power = model.predict(X_test)
predicted_power = scaler.inverse_transform(predicted_power)
# 可视化预测结果
plt.plot(test_set, color='red', label='Real Wind Power')
plt.plot(predicted_power, color='blue', label='Predicted Wind Power')
plt.title('Wind Power Prediction')
plt.xlabel('Time')
plt.ylabel('Wind Power')
plt.legend()
plt.show()
```
其中,`wind_power.csv`文件包含了历史风电功率数据。代码中,我们首先加载数据,然后将数据集拆分为训练集和测试集。接着,我们对训练集进行归一化处理,并将其重塑为LSTM输入格式。然后,我们构建LSTM模型,并使用训练集训练该模型。最后,我们使用测试集进行预测,并将预测结果进行可视化。
阅读全文