【问题标题】:The model I built with 'tf.keras.Sequential()' doesn't work, why?我用 'tf.keras.Sequential()' 建立的模型不起作用,为什么?
【发布时间】:2019-05-20 23:28:28
【问题描述】:

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

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

【问题讨论】:

    标签: tensorflow


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      相关资源
      最近更新 更多