修改上述代码,使得预测结果能和真实值绘图比较
时间: 2024-02-21 18:59:27 浏览: 93
基于遗传算法改进BP神经网络的BS测算值预测(代码完整,数据齐全)
好的,您可以按照以下代码进行修改:
```python
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
import xlrd
import matplotlib.pyplot as plt
# 加载数据
data = pd.read_excel(r"D:\xiangmu\utilits\name_of_your_excel_file3.xls", usecols=[4], nrows=3000, header=None)
dataset = data.values.astype("float32")
# 将数据集分为训练集和测试集
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train_data, test_data = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
# 准备数据
def create_dataset(dataset, window_size=1):
X, Y = [], []
for i in range(len(dataset)-window_size):
X.append(dataset[i:i+window_size, 0])
Y.append(dataset[i+window_size, 0])
return np.array(X), np.array(Y)
window_size = 1
train_X, train_Y = create_dataset(train_data, window_size)
test_X, test_Y = create_dataset(test_data, window_size)
# 创建LSTM模型
model = Sequential()
model.add(LSTM(32, input_shape=(window_size, 1)))
model.add(Dense(1))
model.compile(loss="mean_squared_error", optimizer="adam")
# 训练模型
model.fit(train_X, train_Y, epochs=50, batch_size=1, verbose=2)
# 单步预测
predicted = model.predict(test_X)
# 拟合与预测窗口的大小
fit_size = 500
pred_size = 500
# 完整预测序列
full_predicted = []
for i in range(len(dataset)-fit_size-pred_size):
fit_data = dataset[i:i+fit_size, :]
pred_data = predicted[i:i+pred_size, :]
model.fit(np.reshape(fit_data, (fit_size, window_size, 1)), pred_data, epochs=1, batch_size=1, verbose=0)
full_predicted.append(predicted[i+pred_size-1, 0])
# 将预测结果输出到excel文档中
book = xlrd.open_workbook(r"D:\xiangmu\utilits\name_of_your_excel_file3.xls")
writer = pd.ExcelWriter(r"D:\xiangmu\utilits\name_of_your_excel_file3.xls", engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
result_df = pd.DataFrame(full_predicted, columns=["Predicted"])
result_df.to_excel(writer, sheet_name='Sheet1', startcol=5, startrow=3000, index=False)
writer.save()
# 绘制预测结果与真实值的比较图
plt.plot(test_Y, label="True Data")
plt.plot(predicted, label="Predicted Data")
plt.legend()
plt.show()
```
这个代码会在输出预测结果到Excel文档之后,绘制预测结果与真实值的比较图。您可以通过比较两条曲线来判断模型的预测效果。请注意,在运行此代码之前,您需要安装Matplotlib库。
阅读全文