# 9.绘制结果 plot_size = 200 plt.figure(figsize=(12, 8)) plt.plot(scaler.inverse_transform((model(x_train_tensor).detach().numpy()[: plot_size]).reshape(-1, 1)), "b") plt.plot(scaler.inverse_transform(y_train_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r") plt.legend() plt.show() y_test_pred = model(x_test_tensor) # data是一个以为度得列表 ,这样是把数据写进去一列 print("--------------------------") yuce=scaler.inverse_transform(y_test_pred.detach().numpy()) true=scaler.inverse_transform(y_test_tensor.detach().numpy().reshape(-1, 1)) res = [] for i in range(len(yuce)): temp=[] temp.append(true[i][0]) temp.append(yuce[i][0]) # print() # print(yuce[i][0]) res.append(temp) columns = ['真实值', '预测值'] test = pd.DataFrame(columns=columns, data=res) test.to_csv('jieguo.csv') plt.figure(figsize=(12, 8)) plt.plot(scaler.inverse_transform(y_test_pred.detach().numpy()[: plot_size]), "b") plt.plot(scaler.inverse_transform(y_test_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r") plt.legend() plt.show()
时间: 2024-04-19 13:26:15 浏览: 132
这段代码用于绘制模型的预测结果和真实值,并将结果保存到一个名为"jieguo.csv"的文件中。
首先,我们设置了绘图的尺寸为12x8,并使用蓝色线条绘制了模型对训练数据的预测结果,使用红色线条绘制了真实值。然后,通过调用`plt.legend()`方法添加图例,并通过`plt.show()`显示图形。
接下来,我们使用模型对测试数据进行预测,并使用`scaler.inverse_transform()`方法将预测值和真实值转换回原始数据的尺度。然后,我们将结果保存到一个名为"jieguo.csv"的文件中。
最后,我们再次绘制了模型对测试数据的预测结果和真实值,并通过`plt.legend()`方法添加图例,并通过`plt.show()`显示图形。
请注意,这段代码中的绘图部分可能需要依赖matplotlib库进行绘图操作,请确保已经正确安装并导入该库。另外,代码中涉及到的变量和函数调用需要根据实际情况进行替换。
相关问题
plot_size = 730 plt.figure(figsize=(12, 8)) plt.plot(scaler.inverse_transform((model(x_train_tensor).detach().numpy()[: plot_size]).reshape(-1, 1)), "b") plt.plot(scaler.inverse_transform(y_train_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r") plt.legend() plt.show() y_test_pred = model(x_test_tensor) plt.figure(figsize=(12, 8)) plt.plot(scaler.inverse_transform(y_test_pred.detach().numpy()[: plot_size]), "b") plt.plot(scaler.inverse_transform(y_test_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r") plt.legend() plt.show()这段代码后加上图片保存到文件夹A中,且图片分别以文件名1、文件名2命名
可以在代码中添加如下代码,实现保存图片到文件夹A中,并分别以文件名1、文件名2命名:
```
# 保存训练集预测结果图片
plt.figure(figsize=(12, 8))
plt.plot(scaler.inverse_transform((model(x_train_tensor).detach().numpy()[: plot_size]).reshape(-1, 1)), "b")
plt.plot(scaler.inverse_transform(y_train_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r")
plt.legend()
plt.savefig('./A/文件名1.png')
# 保存测试集预测结果图片
y_test_pred = model(x_test_tensor)
plt.figure(figsize=(12, 8))
plt.plot(scaler.inverse_transform(y_test_pred.detach().numpy()[: plot_size]), "b")
plt.plot(scaler.inverse_transform(y_test_tensor.detach().numpy().reshape(-1, 1)[: plot_size]), "r")
plt.legend()
plt.savefig('./A/文件名2.png')
```
其中,`plt.savefig()`函数可以将图片保存到指定路径和文件名下。需要注意的是,如果`A`文件夹不存在,需要先创建该文件夹,可以使用`os.makedirs()`函数来创建。
import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense data = pd.read_csv('车辆:274序:4结果数据.csv') x = data[['车头间距', '原车道前车速度']].values y = data['本车速度'].values 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)] from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) model = Sequential() model.add(LSTM(50, input_shape=(2, 1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(x_train.reshape(-1, 2, 1), y_train, epochs=100, batch_size=32, validation_data=(x_test.reshape(-1, 2, 1), y_test)) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper right') plt.show() train_predict = model.predict(x_train.reshape(-1, 2, 1)) test_predict = model.predict(x_test.reshape(-1, 2, 1)) train_predict = scaler.inverse_transform(train_predict) train_predict = train_predict.reshape(-1) # 将结果变为一维数组 y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).reshape(-1) # 将结果变为一维数组 test_predict = scaler.inverse_transform(test_predict) y_test = scaler.inverse_transform([y_test]) plt.plot(y_train[0], label='train') plt.plot(train_predict[:,0], label='train predict') plt.plot(y_test[0], label='test') plt.plot(test_predict[:,0], label='test predict') plt.legend() plt.show()报错Traceback (most recent call last): File "C:\Users\马斌\Desktop\NGSIM_data_processing\80s\lstmtest.py", line 42, in <module> train_predict = scaler.inverse_transform(train_predict) File "D:\python\python3.9.5\pythonProject\venv\lib\site-packages\sklearn\preprocessing\_data.py", line 541, in inverse_transform X -= self.min_ ValueError: non-broadcastable output operand with shape (611,1) doesn't match the broadcast shape (611,2)
这个错误发生在将归一化后的预测结果进行逆归一化时。根据错误提示,训练集的预测结果和真实值的形状为 (611,),而测试集的预测结果和真实值的形状为 (1, 611)。这是因为在进行逆归一化时,要求预测结果和真实值的形状必须一致,即都为一维数组。
你可以将 y_test 的形状改为 (611,),方法是将 y_test 的数据类型从二维数组转换为一维数组,就像对 y_train 做的那样。修改后的代码如下:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
data = pd.read_csv('车辆:274序:4结果数据.csv')
x = data[['车头间距', '原车道前车速度']].values
y = data['本车速度'].values
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)]
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
model = Sequential()
model.add(LSTM(50, input_shape=(2, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
history = model.fit(x_train.reshape(-1, 2, 1), y_train, epochs=100, batch_size=32, validation_data=(x_test.reshape(-1, 2, 1), y_test))
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()
train_predict = model.predict(x_train.reshape(-1, 2, 1))
test_predict = model.predict(x_test.reshape(-1, 2, 1))
train_predict = scaler.inverse_transform(train_predict)
train_predict = train_predict.reshape(-1) # 将结果变为一维数组
y_train = scaler.inverse_transform(y_train.reshape(-1, 1)).reshape(-1) # 将结果变为一维数组
test_predict = scaler.inverse_transform(test_predict)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).reshape(-1) # 将结果变为一维数组
plt.plot(y_train, label='train')
plt.plot(train_predict, label='train predict')
plt.plot(y_test, label='test')
plt.plot(test_predict, label='test predict')
plt.legend()
plt.show()
```
阅读全文