Mashiro
Mashiro

Reputation: 3

The model I built with 'tf.keras.Sequential()' doesn't work, why?

When I tried to train the model I built, I found that the loss and accuracy have not changed.

import tensorflow as tf
tf.enable_eager_execution()

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

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

model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

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

This is the result:

Epoch 1/5 60000/60000 [==============================] - 7s 123us/sample - loss: 12.9310 - acc: 0.1975 
Epoch 2/5 60000/60000 [==============================] - 5s 87us/sample - loss: 12.8994 - acc: 0.1997 
Epoch 3/5 60000/60000 [==============================] - 5s 85us/sample - loss: 12.9162 - acc: 0.1986 
Epoch 4/5 60000/60000 [==============================] - 5s 84us/sample - loss: 12.9052 - acc: 0.1993 
Epoch 5/5 60000/60000 [==============================] - 5s 84us/sample - loss: 12.9052 - acc: 0.1993

Upvotes: 0

Views: 269

Answers (1)

Anubhav Singh
Anubhav Singh

Reputation: 8699

You forgot to scale values to a range of 0 to 1 before feeding to the neural network model.

Code:

import tensorflow as tf

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

train_images = train_images / 255.0
test_images = test_images / 255.0

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

model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

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

Output:

Epoch 1/5
60000/60000 [==============================] - 5s 91us/step - loss: 0.4977 - acc: 0.8267
Epoch 2/5
60000/60000 [==============================] - 5s 85us/step - loss: 0.3745 - acc: 0.8652
Epoch 3/5
60000/60000 [==============================] - 5s 89us/step - loss: 0.3334 - acc: 0.8794
Epoch 4/5
60000/60000 [==============================] - 6s 93us/step - loss: 0.3103 - acc: 0.8874
Epoch 5/5
60000/60000 [==============================] - 5s 86us/step - loss: 0.2934 - acc: 0.8913

Upvotes: 1

Related Questions