绘制LSTM预测结果时报错:x和y维度不能超过2D
解决LSTM预测结果绘图的ValueError问题
尝试绘制LSTM模型预测结果时,运行以下代码触发错误且仅显示真实值曲线:
y_pred_FF = model_LSTM.predict(X_test.reshape(X_test.shape[0],1)) plt.plot(y_test, "b-+", label='Ground truth', color = "red") plt.plot(y_pred_FF, "b-", label='Feed Forward prediction', color = "blue") plt.legend() plt.ylim(0,18) plt.xlim(0, 200) plt.xlabel('Time instances', fontsize=16) plt.ylabel('Activity', fontsize=16) plt.grid() plt.show()
错误信息:
ValueError: x and y can be no greater than 2D, but have shapes (14152,) and (14152, 1, 1)
问题原因
y_pred_FF是3维数组(形状(14152,1,1)),而y_test是1维数组(形状(14152,)),matplotlib要求绘图的y值维度匹配,否则无法正常渲染预测曲线。
解决方法
将预测结果降维为1维即可,两种常用方式:
方式1:使用squeeze()去除多余维度
修改预测代码或在绘图前处理:
# 方法一:预测时直接降维 y_pred_FF = model_LSTM.predict(X_test.reshape(X_test.shape[0],1)).squeeze() # 方法二:单独处理预测结果 y_pred_FF = model_LSTM.predict(X_test.reshape(X_test.shape[0],1)) y_pred_FF = y_pred_FF.squeeze()
方式2:通过数组索引提取有效数据
直接取数组的对应维度值:
y_pred_FF = model_LSTM.predict(X_test.reshape(X_test.shape[0],1))[:, 0, 0]
处理后y_pred_FF的形状会变为(14152,),和y_test维度一致,运行代码即可正常显示两条曲线。
内容的提问来源于stack exchange,提问作者Innana
相关产品推荐
相关产品推荐

