我有训练功能和测试功能数组,它们分别为两列,而训练标签和测试标签分别为3列。在预测了两列测试标签之后,我返回了一个三列数组。尝试执行evaluate()
会引发异常ValueError: Error when checking input: expected dense_30_input to have shape (2,) but got array with shape (3,)
。我不明白,因为我希望它评估形状3的数组?下面是代码:
import keras
from keras.models import Sequential
from keras.layers import Dense
# Define the model
ann = Sequential()
ann.add(Dense(50, input_dim=2, activation='relu'))
ann.add(Dense(100, activation='relu'))
ann.add(Dense(50, activation='relu'))
ann.add(Dense(3, activation='softmax'))
ann.compile(loss="mean_squared_error", optimizer='adam', metrics = ['accuracy'])
ann.fit(train_features, train_labels, batch_size = 1, epochs = 500)
# making predictions
predictions = ann.predict(test_features)
score = ann.evaluate(test_labels, predictions, batch_size=128)
这是数据的样子:
train_features:
[[0.7545026 0.79279279]
[0.46078708 0.05405405]
[0.41855151 0.38738739]
[0.74803041 0.28828829]
[1. 0. ]
[0.03371062 0.51351351]
[0.63705531 0.6036036 ]
[0.55073228 1. ]
[0.18877317 0.12612613]
[0.0903093 0.51351351]
[0. 0.9009009 ]
[0.64266119 0.95495495]
[0.23438608 0.12612613]
[0.13543883 0.24324324]]
test_features:
[[0.28072092 0.00900901]
[0.17869765 0.66666667]
[0.8620313 0.1981982 ]
[0.34786594 0.03603604]]
train_labels
[[1. 0.5 1. ]
[0. 0.5 0.66666667]
[0. 0. 1. ]
[1. 1. 0.66666667]
[1. 1. 1. ]
[1. 0. 0. ]
[0. 1. 0.66666667]
[1. 0.5 0.66666667]
[1. 0. 1. ]
[0. 0.5 0. ]
[0. 0. 0. ]
[0. 0.5 1. ]
[1. 1. 0. ]
[1. 0.5 0. ]]
test_labels
[[0. 0. 0.66666667]
[0. 1. 0. ]
[0. 1. 1. ]
[1. 0. 0.66666667]]
predictions
[[0.07219139 0.9239723 0.00383623]
[0.11950634 0.53162473 0.3488689 ]
[0.5265181 0.35849473 0.1149871 ]
[0.01260971 0.9338486 0.05354166]]
答案 0 :(得分:1)
我建议您看看evaluate
方法的documentation。
ann.evaluate(test_features, test_labels)
是要走的路。
它将直接使用模型进行预测,这就是为什么它要求您输入shape (2,)
(即您的输入形状)的原因。
为了使所有内容都清楚,问题不在于培训/测试中的示例数量,它们可以不同,问题在于示例的维度。您的模型需要二维输入,并且评估方法的第一个参数应该是测试数据的数组,而不是该测试数据的真实标签或预测输出。