Keras model evaluation shows a TypeError: 'numpy.float64' object is not iterable for mnist dataset

旧街凉风 提交于 2020-01-02 17:56:32

问题


I just got started with keras, and I tried to build a model for the mnist dataset in the keras.datasets

Here's my initial code:

import tensorflow as tf

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

Then, I defined a model:

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)

I tried this model using model.compile(loss = 'sparse_categorical_crossentropy', optimizer='rmsprop') and the model just trained fine

Later, I tried to evaluate the model:

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

and it showed the following error:

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

But, when I try to make predictions on the test_images by using predictions = model.predict(test_images), it works fine.

I'm using google colab to code. Please Help!


回答1:


Your model has no metrics as a result of lack of metrics parameter of your model.compile()

Compile

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

call, thus as per the documentation :

Returns

Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.

Keras model evaluate() returns only loss.

So if you alter your code:

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

you can get accuracy too.



来源:https://stackoverflow.com/questions/53582005/keras-model-evaluation-shows-a-typeerror-numpy-float64-object-is-not-iterable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!