You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.1 KiB

6 months ago
import keras
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.layers import Dense, LSTM, Activation, Dropout
from keras.optimizers import SGD
colum = 13
step = 50
df = pd.read_csv('文件名')
df_for_training=df[:24000]
df_for_testing=df[24000:]
# print(df_for_testing.iloc[:, 2:])
scaler = MinMaxScaler(feature_range=(-1, 1))
df_for_training_scaled = scaler.fit_transform(df_for_training.iloc[:, 2:])
print("df_for_training_scaled shape:",df_for_training_scaled.shape)
#print(df_for_training_scaled.shape)
#print(df_for_testing_scaled.shape)
#抽取特征与标签列
def createXY(dataset, n_past):
dataX = []
dataY = []
for i in range(n_past, len(dataset)):
dataX.append(dataset[i - n_past:i, 1:dataset.shape[1]])
dataY.append(dataset[i, 0])
return np.array(dataX), np.array(dataY)
#trainX,testX数据的shape为[samples, steps, features]
trainX, trainY = createXY(df_for_training_scaled, step)
testX, testY = createXY(df_for_testing_scaled, step)
#构建模型
def build_model():
model = tf.keras.models.Sequential()
#经试验如果下一层还是LSTM的话必须将return_sequences设置为True
model.add(LSTM(20, input_shape=(step, column), return_sequences=True))
model.add(LSTM(20))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mae', optimizer=SGD(lr=0.1,momentum=0.3))
return model
lstm_net = build_model()
lstm_net.fit(trainX, trainY, batch_size=8, epochs=100)
predictions = lstm_net.predict(testX)
#进行逆变换
test_Predict_copy = np.repeat(predictions,column+1,axis=-1)
test_Predict_inverse = scaler.inverse_transform(test_Predict_copy)[:,0]
#test_Predict_inverse = scaler.inverse_transform(test_Predict)
test_label = np.array(df_for_testing['omega_vsg_1'])[50:]
testY_copy = np.repeat(np.reshape(testY,(len(testY), 1)),column+1,axis=-1)
testY_inverse = scaler = scaler.inverse_transform(testY_copy)[:,0]
plt.plot(test_Predict_inverse,color='red')
plt.plot(test_label,color='green')
plt.plot(testY_inverse, color='blue')
plt.savefig('result_test.png')