为什么在相同的x_train下,model.predict()的精度比model.fit()差



images接收加载了cv2 的图像阵列

images=np.array(images)
labels=np.array(labels)
idLabels=[]
for i in labels:
idLabels.append(dicTipos[i])
labels=np.array(idLabels)
images = np.array(images, dtype = 'float32')
print("images done")
print("labels", labels)
labels = np.array(labels, dtype = 'int32')

x_train=images
y_train=labels

我定义了模型,然后我使用fit((

model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10)

输出的最后一行是:

Epoch 10/10
25/25 [==============================] - 101s 4s/step - loss: 0.0047 - accuracy: 0.9987

我立即使用predict((函数,精度真的很差:

predicted=model.predict(x_train)
rounded_predictions=np.argmax(predicted,axis=1)
temp = sum(y_train == rounded_predictions)
temp=temp/len(y_train)
print("Accuracy:  ", temp)

输出:

Accuracy:   0.12625

我不知道为什么如果我设置相同的x_train用于训练,并且设置相同的x_train用于测试,会发生这种情况(精度比拟合差(

您应该直接使用与模型一起编译的准确性度量。这将确保您在培训和测试时以相同的方式评估准确性

尝试:

perf = model.evaluate(x_train, y_train,return_dict = True)
print (perf)

最新更新