plt.figure(figsize=(40,20)) if forecasting_model == 'multi_steps': plt.plot(pre_array[0], 'g') plt.plot(test_labels[0].cpu(), "r") plt.show() else: plt.plot(pre_array, 'g') plt.plot(test_labels.cpu(), "r") plt.show() MSE_l = mean_squared_error(test_labels.cpu(), pre_array) MAE_l = mean_absolute_error(test_labels.cpu(), pre_array) MAPE_l = mean_absolute_percentage_error(test_labels.cpu(), pre_array) R2 = r2_score(test_labels.cpu(), pre_array) print('MSE loss=%s'%MSE_l) print('MAE loss=%s'%MAE_l) print('MAPE loss=%s'%MAPE_l) print('R2=%s'%R2)
时间: 2024-03-07 14:52:07 浏览: 497
这段代码的作用是绘制预测结果与真实标签值的折线图,并计算预测结果的MSE、MAE、MAPE和R2指标。其中,`pre_array`是模型的预测结果,`test_labels`是真实标签值,`forecasting_model`是一个字符串变量,表示预测模型的类型。如果预测模型是`multi_steps`(多步预测模型),则绘制预测结果的第一条线,否则绘制整个预测结果序列的折线图。然后,绘制真实标签值的折线图,并显示图像。接着,计算MSE、MAE、MAPE和R2指标,并将它们打印出来。
相关问题
import numpy as np import matplotlib.pyplot as plt import pickle as pkl import pandas as pd import tensorflow.keras from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import LSTM, GRU, Dense, RepeatVector, TimeDistributed, Input, BatchNormalization, \ multiply, concatenate, Flatten, Activation, dot from sklearn.metrics import mean_squared_error,mean_absolute_error from tensorflow.keras.optimizers import Adam from tensorflow.python.keras.utils.vis_utils import plot_model from tensorflow.keras.callbacks import EarlyStopping from keras.callbacks import ReduceLROnPlateau df = pd.read_csv('lorenz.csv') signal = df['signal'].values.reshape(-1, 1) x_train_max = 128 signal_normalize = np.divide(signal, x_train_max) def truncate(x, train_len=100): in_, out_, lbl = [], [], [] for i in range(len(x) - train_len): in_.append(x[i:(i + train_len)].tolist()) out_.append(x[i + train_len]) lbl.append(i) return np.array(in_), np.array(out_), np.array(lbl) X_in, X_out, lbl = truncate(signal_normalize, train_len=50) X_input_train = X_in[np.where(lbl <= 9500)] X_output_train = X_out[np.where(lbl <= 9500)] X_input_test = X_in[np.where(lbl > 9500)] X_output_test = X_out[np.where(lbl > 9500)] # Load model model = load_model("model_forecasting_seq2seq_lstm_lorenz.h5") opt = Adam(lr=1e-5, clipnorm=1) model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mae']) #plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True) # Train model early_stop = EarlyStopping(monitor='val_loss', patience=20, verbose=1, mode='min', restore_best_weights=True) #reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=9, verbose=1, mode='min', min_lr=1e-5) #history = model.fit(X_train, y_train, epochs=500, batch_size=128, validation_data=(X_test, y_test),callbacks=[early_stop]) #model.save("lstm_model_lorenz.h5") # 对测试集进行预测 train_pred = model.predict(X_input_train[:, :, :]) * x_train_max test_pred = model.predict(X_input_test[:, :, :]) * x_train_max train_true = X_output_train[:, :] * x_train_max test_true = X_output_test[:, :] * x_train_max # 计算预测指标 ith_timestep = 10 # Specify the number of recursive prediction steps # List to store the predicted steps pred_len =2 predicted_steps = [] for i in range(X_output_test.shape[0]-pred_len+1): YPred =[],temdata = X_input_test[i,:] for j in range(pred_len): Ypred.append (model.predict(temdata)) temdata = [X_input_test[i,j+1:-1],YPred] # Convert the predicted steps into numpy array predicted_steps = np.array(predicted_steps) # Plot the predicted steps #plt.plot(X_output_test[0:ith_timestep], label='True') plt.plot(predicted_steps, label='Predicted') plt.legend() plt.show()
这段代码看起来是一个用于时间序列预测的深度学习模型。该模型使用了序列到序列 LSTM (Seq2Seq LSTM) 模型进行预测,使用了 EarlyStopping 回调函数来避免过度拟合,并使用 Adam 优化器来进行模型优化。
具体来说,该代码读取了一个名为 'lorenz.csv' 的数据文件,将其中的信号列读取出来并进行了归一化处理。然后,使用 truncate 函数将信号序列切割成训练集和测试集,将其输入到 Seq2Seq LSTM 模型中进行训练。训练完成后,对测试集进行预测并计算预测指标,最后使用 matplotlib 库将预测结果可视化。
如果需要更详细的解释或修改建议,请提出具体问题或要求。
阅读全文