Search code examples
pythontensorflowkerasdeep-learningartificial-intelligence

How to fix a TypeError in this tensorflow code?


The code:

import tensorflow as tf
from tensorflow import keras


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

model = keras.Sequential([
    keras.layers.Flatten(input_shape = (28,28)),
    keras.layers.Dense(128,activation = tf.nn.relu),
    keras.layers.Dense(10,activation = tf.nn.softmax)
])

model.compile(optimizer=tf.optimizers.Adam(),),
              loss = 'sparse_categorical_crossentropy')

model.fit(train_images,train_labels,epochs = 5)

test_loss, test_acc = model.evaluate (test_images, test_labels)

First, I had 'AttributeError: module 'tensorflow._api.v2.train' has no attribute 'AdamOptimizer'' and changed 'optimizer=tf.train.AdamOptimizer()' to 'tf.optimizers.Adam()' (worked) and then i had another error.(Found solution at [https://stackoverflow.com/questions/55318273/tensorflow-api-v2-train-has-no-attribute-adamoptimizer] )

The error:

line 25, in <module> test_loss, test_acc = model.evaluate(test_images, test_labels) ^^^^^^^^^^^^^^^^^^^ TypeError: cannot unpack non-iterable float object

Here is what ChatGPT advised me (also didn't work):

import tensorflow as tf
from tensorflow import keras


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

# Reshape the input data
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1)

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28,28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy')

model.fit(train_images, train_labels, epochs=5)

# Reshape the test data
test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)

test_loss, test_acc = model.evaluate(test_images, test_labels)

also all the code I took from the Zero to Hero tensorflow YT videos


Solution

  • Add 'accuracy' metric in compile:

    model.compile(optimizer=tf.optimizers.Adam(),
                  loss='sparse_categorical_crossentropy',
                  metrics=['acc'])
    

    You will get only loss value without it.