【问题标题】:Keras model evaluation shows a TypeError: 'numpy.float64' object is not iterable for mnist datasetKeras 模型评估显示 TypeError: 'numpy.float64' object is not iterable for mnist dataset
【发布时间】:2019-05-04 01:17:13
【问题描述】:

我刚开始使用keras,我尝试为keras.datasets中的mnist数据集构建模型

这是我的初始代码:

import tensorflow as tf

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

然后,我定义了一个模型:

model = tf.keras.Sequential()

model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(512, activation = tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation = tf.nn.softmax))

model.compile(loss = 'sparse_categorical_crossentropy', optimizer='rmsprop')
model.fit(train_images, train_labels, epochs=10)

我使用model.compile(loss = 'sparse_categorical_crossentropy', optimizer='rmsprop') 尝试了这个模型,并且模型训练得很好

后来,我尝试评估模型:

loss, accuracy = model.evaluate(test_images, test_labels)
print('Accuracy on the test set: '+str(accuracy))

它显示了以下错误

10000/10000 [==============================] - 0s 50us/step
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-7ccd830be0cb> in <module>()
----> 1 loss, accuracy = model.evaluate(test_images, test_labels)
      2 print('Accuracy on the test set: '+str(accuracy))

TypeError: 'numpy.float64' object is not iterable

但是,当我尝试使用 predictions = model.predict(test_images) 对 test_images 进行预测时,它工作正常。

我正在使用 google colab 进行编码。 请帮忙!

【问题讨论】:

  • 我没有看到你的 model.fit() 方法。
  • 对不起,我已经在代码中找到了,但我忘了在帖子中包含它

标签: python tensorflow keras deep-learning google-colaboratory


【解决方案1】:

由于您的 model.compile() 缺少 metrics 参数,您的模型没有指标

编译

compile(optimizer, loss=None, metrics=None, loss_weights=None, sample_weight_mode=None, weighted_metrics=None, target_tensors=None)

调用,因此根据documentation

退货

标量测试损失(如果模型只有一个输出并且没有指标)或 标量列表(如果模型有多个输出和/或指标)。 属性 model.metrics_names 将为您提供显示标签 标量输出。

Keras 模型 evaluate() 只返回损失。

所以如果你改变你的代码:

model.compile(loss='sparse_categorical_crossentropy', metrics=['accuracy'], optimizer='rmsprop')

您也可以获得准确性

【讨论】:

  • 它对我有用,但有一点小修正。您必须将“准确性”作为列表元素传递给矩阵;也就是说,metrics=['accuracy'] 而不仅仅是 metrics='accuracy'
  • @SurajSJain 是的,谢谢,很好的评论,正如我在上面链接的文档中一样,可以阅读。我错过了,对不起,我会更新我的答案。
猜你喜欢
  • 2022-12-26
  • 2021-04-09
  • 2016-09-25
  • 2020-09-28
  • 2021-01-06
  • 2020-06-11
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多