我使用“ tf.keras.Sequential()”构建的模型不起作用,为什么?

时间:2019-05-20 05:03:27

标签: tensorflow

当我尝试训练自己建立的模型时,我发现损失和准确性没有改变。

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)

这是结果:

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

1 个答案:

答案 0 :(得分:1)

在输入神经网络模型之前,您忘记将值缩放到0到1的范围。

代码:

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)

输出:

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