为什么 model.predict() 在 x_train 的情况下比 model.fit() 更差?

Why model.predict() is getting worse accuracy than model.fit() with the same x_train?

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)