计算均方误差时返回 y_true 和 y_pred 的输出数量不同(1!=10)

我对深度学习还很新手。我想完成一个任务,任务要求如下:在测试数据上评估模型,并计算预测的混凝土强度与实际混凝土强度之间的均方误差。你可以使用 Scikit-learn 中的 mean_squared_error 函数。

这是我的代码:

import pandas as pdfrom tensorflow.python.keras import Sequentialfrom tensorflow.python.keras.layers import Densefrom sklearn.model_selection import train_test_splitconcrete_data = pd.read_csv('https://cocl.us/concrete_data')n_cols = concrete_data.shape[1]model = Sequential()model.add(Dense(units=10, activation='relu', input_shape=(n_cols-1,)))model.compile(loss='mean_squared_error',          optimizer='adam')y = concrete_data.Cementx = concrete_data.drop('Cement', axis=1)xTrain, xTest, yTrain, yTest = train_test_split(x, y, test_size = 0.3)model.fit(xTrain, yTrain, epochs=50)

现在为了评估均方误差,我编写了如下代码:

from sklearn.metrics import mean_squared_errorpredicted_y = model.predict(xTest)mean_squared_error(yTest, predicted_y)

然后我得到了这个错误:

y_true and y_pred have different number of output (1!=10)

我的 predicted_y 的形状是:(309, 10)

我上网搜索了很久,但实在找不到解决这个问题的答案。我不知道我的代码哪里出了问题。


回答:

你的 y_test 数据形状是 (N, 1),但因为你在输出层设置了10个神经元,你的模型会做出10个不同的预测,这就是错误的原因。

你需要将输出层的神经元数量改为1,或者添加一个新的输出层,该层只有1个神经元。

下面的代码可能会对你有帮助。

import pandas as pdfrom tensorflow.python.keras import Sequentialfrom tensorflow.python.keras.layers import Densefrom sklearn.model_selection import train_test_splitconcrete_data = pd.read_csv('https://cocl.us/concrete_data')n_cols = concrete_data.shape[1]model = Sequential()model.add(Dense(units=10, activation='relu', input_shape=(n_cols-1,)))           model.add(Dense(units=1))model.compile(loss='mean_squared_error',          optimizer='adam')y = concrete_data.Cementx = concrete_data.drop('Cement', axis=1)xTrain, xTest, yTrain, yTest = train_test_split(x, y, test_size = 0.3)model.fit(xTrain, yTrain, epochs=50)

Related Posts

如何从数据集中移除EXIF数据?

我在尝试从数据集中的图像中移除EXIF数据(这些数据将…

用于Python中的“智能点”游戏的遗传算法不工作

过去几天我一直在尝试实现所谓的“智能点”游戏。我第一次…

哪个R平方得分更有帮助?

data.drop(‘Movie Title’, ax…

使用线性回归预测GRE分数对录取率的影响

我正在学习线性回归,并尝试在Jupyter笔记本中用P…

使用mlrMBO贝叶斯优化进行SVM超参数调优时出现错误

我试图针对一个分类任务优化SVM,这个方法在许多其他模…

Keras模型的二元交叉熵准确率未发生变化

我在网上看到了很多关于这个问题的提问,但没有找到明确的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注