lstm对风电功率短期预测python代码
时间: 2023-06-23 09:08:53 浏览: 175
以下是使用LSTM实现风电功率短期预测的Python代码:
```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
# 读取数据
df = pd.read_csv('wind_power.csv', header=0, index_col=0)
df.index = pd.to_datetime(df.index)
df = df.resample('H').mean()
# 特征工程
df['Weekday'] = df.index.dayofweek
df['Hour'] = df.index.hour
df['Month'] = df.index.month
# 归一化
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df[['Power', 'Weekday', 'Hour', 'Month']])
# 划分训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size, :]
test_data = scaled_data[train_size:, :]
# 定义函数创建数据集
def create_dataset(dataset, look_back=1):
data_X, data_Y = [], []
for i in range(len(dataset) - look_back):
data_X.append(dataset[i:(i + look_back), :])
data_Y.append(dataset[i + look_back, 0])
return np.array(data_X), np.array(data_Y)
# 创建训练集和测试集
look_back = 24
train_X, train_Y = create_dataset(train_data, look_back)
test_X, test_Y = create_dataset(test_data, look_back)
# 定义LSTM模型
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=64, validation_data=(test_X, test_Y), verbose=2, shuffle=False)
# 预测测试集
test_predict = model.predict(test_X)
test_predict = np.concatenate((test_predict, test_X[:, -1, 1:]), axis=1)
test_predict = scaler.inverse_transform(test_predict)[:, 0]
# 画出预测结果
import matplotlib.pyplot as plt
plt.plot(df.index[train_size + look_back:], test_Y, label='True Data')
plt.plot(df.index[train_size + look_back:], test_predict, label='Predict Data')
plt.legend()
plt.show()
```
其中,`wind_power.csv`是风电功率数据,包括`Power`、`Weekday`、`Hour`和`Month`四个特征。首先读取数据并进行特征工程和归一化处理,然后使用函数`create_dataset`将数据集转化为LSTM的输入格式。接着定义LSTM模型并进行训练,最后预测测试集并反归一化得到预测结果,最后画出预测结果。
阅读全文