数据和整理好的jupyter文件在这里下载
https://download.csdn.net/download/k54kdk/87770077https://download.csdn.net/download/k54kdk/87770077
✦ 数据预处理✦
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
data = pd.read_csv('data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['data'].values.reshape(-1, 1))
✦划分数据集✦
def create_dataset(scaled_data, look_back=4):
dataX, dataY = [], []
for i in range(len(scaled_data) - look_back):
dataX.append(scaled_data[i:(i + look_back), 0])
dataY.append(scaled_data[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 2
X, y = create_dataset(scaled_data, look_back)
X = np.reshape(X, (X.shape[0], 1, X.shape[1]))
def predict_future(model, last_data, n_future, look_back):
future_predictions = []
current_input = np.array(last_data).reshape(1, 1, look_back)
for _ in range(n_future):
prediction = model.predict(current_input)
future_predictions.append(prediction[0, 0])
current_input = np.append(current_input[0, 0, 1:], prediction).reshape(1, 1, look_back)
return np.array(future_predictions)
✦创建LSTM模型与训练✦
model = Sequential()
model.add(LSTM(50, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
# 训练模型
model.fit(X, y, epochs=250, batch_size=1, verbose=0)
✦预测数据✦
train_predictions = model.predict(X)
train_predictions = scaler.inverse_transform(train_predictions)
# 预测未来10年
n_future = 10
future_predictions = predict_future(model, scaled_data[-look_back:], n_future, look_back)
future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1))
✦计算误差✦
real_values = data['data'][look_back:].values
absolute_errors = np.abs(real_values - train_predictions.reshape(-1))
relative_errors = absolute_errors / real_values
error_df = pd.DataFrame({'Real Value': real_values,
'Predicted Value': train_predictions.reshape(-1),
'Absolute Error': absolute_errors,
'Relative Error': relative_errors})
✦创建与训练BP神经网络模型✦
bp_model = Sequential()
bp_model.add(Dense(128, input_dim=look_back, activation='relu'))
bp_model.add(Dense(64, activation='relu'))
bp_model.add(Dense(1))
bp_model.compile(loss='mse', optimizer='adam')
# 训练BP神经网络模型
bp_model.fit(X.reshape(X.shape[0], X.shape[2]), y, epochs=10, batch_size=1, verbose=0)
✦预测数据✦
bp_train_predictions = bp_model.predict(X.reshape(X.shape[0], X.shape[2]))
bp_train_predictions = scaler.inverse_transform(bp_train_predictions)
# 预测未来10年
bp_future_predictions = predict_future(bp_model, scaled_data[-look_back:], n_future, look_back)
bp_future_predictions = scaler.inverse_transform(bp_future_predictions.reshape(-1, 1))
✦可视化结果✦
plt.plot(data['data'], label='Real Data')
plt.plot(list(range(look_back, len(data['data']))), train_predictions, label='LSTM Predicted Data (Train)')
plt.plot(list(range(look_back, len(data['data']))), bp_train_predictions, label='BP Predicted Data (Train)', linestyle='--')
plt.plot(list(range(len(data['data']), len(data['data']) + n_future)), future_predictions, label='LSTM Predicted Data (Future)')
plt.plot(list(range(len(data['data']), len(data['data']) + n_future)), bp_future_predictions, label='BP Predicted Data (Future)', linestyle='--')
plt.xlabel('Year Index')
plt.ylabel('Electricity Charge')
plt.legend()
plt.show()
✦误差对比✦
bp_real_values = data['data'][look_back:].values
bp_absolute_errors = np.abs(bp_real_values - bp_train_predictions.reshape(-1))
bp_relative_errors = bp_absolute_errors / bp_real_values
bp_error_df = pd.DataFrame({'Real Value': bp_real_values,
'Predicted Value': bp_train_predictions.reshape(-1),
'Absolute Error': bp_absolute_errors,
'Relative Error': bp_relative_errors})
print("LSTM Model Errors:")
print(error_df)
print("\nBP Neural Network Model Errors:")
print(bp_error_df)
lstm_mean_relative_error = np.mean(relative_errors)
bp_mean_relative_error = np.mean(bp_relative_errors)
print("\nLSTM Model Mean Relative Error:", lstm_mean_relative_error)
print("BP Neural Network Model Mean Relative Error:", bp_mean_relative_error)