【问题标题】:Why model.predict() is getting worse accuracy than model.fit() with the same x_train?为什么 model.predict() 的准确性比具有相同 x_train 的 model.fit() 更差?
【发布时间】:2022-01-04 16:40:13
【问题描述】:

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,我不知道为什么会发生这种情况(比拟合更差)

【问题讨论】:

  • 请尝试model.evaluate(x_train, y_train),并用结果更新您的帖子(不确定您在predict 之后所做的是否正确)。
  • 我会试试的。在predict() 之后,它收到了softmax 的预测,因为我的模型有最后一层model.add(layers.Dense(8, activation='softmax')),所以我得到了x_train 的类索引。
  • 再次,model.evaluate(x_train, y_train) 的结果是什么?
  • 7/7 [==============================] - 4s 589ms/step - loss: 136.1504 - accuracy: 0.1250 那是输出。我在我的模型中使用批量标准化,我读到这可能会影响,但我不明白为什么

标签: python machine-learning keras predict


【解决方案1】:

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

试试:

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

【讨论】:

  • 我是新手,我应该在哪里设置评估()的准确度指标?我在 model.compile 中设置了它,就像我展示的那样使用 fit ,但我不确定你是否是这个意思。这两行的输出是7/7 [==============================] - 5s 627ms/step - loss: 146.0991 - accuracy: 0.1250 {'loss': 146.09913635253906, 'accuracy': 0.125}
猜你喜欢
  • 2021-03-04
  • 2016-10-24
  • 2021-02-13
  • 2021-10-26
  • 2014-11-13
  • 1970-01-01
  • 2019-08-03
  • 2018-07-27
  • 2019-08-29
相关资源
最近更新 更多