上面代码预测图形的真实值都是零 请改正
时间: 2024-04-13 13:30:01 浏览: 101
非常抱歉,我之前的回答有误。以下是修正后的代码,将正确的目标变量与预测结果进行绘图。
```python
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
# 从Excel文件加载数据
def load_data(file_path):
data = pd.read_excel(file_path)
return data.values
# 归一化数据
def normalize_data(data):
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(data)
return scaled_data, scaler
# 反归一化数据
def denormalize_data(scaled_data, scaler):
data = scaler.inverse_transform(scaled_data)
return data
# 创建数据集
def create_dataset(data, look_back):
X, Y = [], []
for i in range(len(data)-look_back-1):
X.append(data[i:(i+look_back), :-1])
Y.append(data[(i+look_back):(i+look_back+2), -1])
return np.array(X), np.array(Y)
# 加载数据
data = load_data('data.xlsx')
# 设置随机种子
tf.random.set_seed(0)
# 定义超参数
look_back = 2 # 时间步数
n_features = 6 # 输入特征量个数
# 归一化数据
scaled_data, scaler = normalize_data(data)
# 创建数据集
X, Y = create_dataset(scaled_data, look_back)
# 划分训练集和测试集
train_size = int(len(X) * 0.7)
test_size = len(X) - train_size
X_train, X_test = X[0:train_size], X[train_size:len(X)]
Y_train, Y_test = Y[0:train_size], Y[train_size:len(Y)]
# 构建LSTM模型
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(64, input_shape=(look_back, n_features)),
tf.keras.layers.Dense(2)
])
# 编译模型
model.compile(optimizer=tf.keras.optimizers.Adam(), loss='mean_squared_error')
# 训练模型
model.fit(X_train, Y_train, epochs=100, batch_size=16)
# 预测数据
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 反归一化数据
train_predict = denormalize_data(train_predict, scaler)
test_predict = denormalize_data(test_predict, scaler)
Y_test = denormalize_data(Y_test, scaler)
# 输出预测数据
print("训练集预测结果:")
print(train_predict)
print("测试集预测结果:")
print(test_predict)
# 输出预测图形
plt.plot(Y_test[:, 0], label='Actual AQI (t+1)')
plt.plot(Y_test[:, 1], label='Actual AQI (t+2)')
plt.plot(test_predict[:, 0], label='Predicted AQI (t+1)')
plt.plot(test_predict[:, 1], label='Predicted AQI (t+2)')
plt.legend()
plt.show()
```
修改后的代码会绘制真实值和预测值的曲线。希望这次能够得到正确的结果。如果还有其他问题,请随时提出。
阅读全文