问题
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