Tensorflow基础:第一个训练模型

模型代码:

import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

# 引入数据
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# 数据处理
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='relu'),
    tf.keras.layers.Dense(10)
])

# 模型编译
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# 训练模型
model.fit(train_images, train_labels, epochs=10, validation_data = (test_images, test_labels))

显示结果:

Epoch 1/10
1875/1875 [==============================] - 2s 705us/step - loss: 0.5012 - accuracy: 0.8230 - val_loss: 0.4400 - val_accuracy: 0.8402
Epoch 2/10
1875/1875 [==============================] - 2s 993us/step - loss: 0.3734 - accuracy: 0.8654 - val_loss: 0.4012 - val_accuracy: 0.8570
Epoch 3/10
1875/1875 [==============================] - 2s 825us/step - loss: 0.3359 - accuracy: 0.8770 - val_loss: 0.4043 - val_accuracy: 0.8519
Epoch 4/10
1875/1875 [==============================] - 1s 617us/step - loss: 0.3126 - accuracy: 0.8848 - val_loss: 0.3465 - val_accuracy: 0.8774
Epoch 5/10
1875/1875 [==============================] - 1s 613us/step - loss: 0.2929 - accuracy: 0.8923 - val_loss: 0.3785 - val_accuracy: 0.8618
Epoch 6/10
1875/1875 [==============================] - 1s 693us/step - loss: 0.2782 - accuracy: 0.8977 - val_loss: 0.3642 - val_accuracy: 0.8747
Epoch 7/10
1875/1875 [==============================] - 1s 778us/step - loss: 0.2663 - accuracy: 0.9009 - val_loss: 0.3756 - val_accuracy: 0.8638
Epoch 8/10
1875/1875 [==============================] - 1s 686us/step - loss: 0.2580 - accuracy: 0.9042 - val_loss: 0.3553 - val_accuracy: 0.8754
Epoch 9/10
1875/1875 [==============================] - 1s 684us/step - loss: 0.2468 - accuracy: 0.9079 - val_loss: 0.3338 - val_accuracy: 0.8844
Epoch 10/10
1875/1875 [==============================] - 1s 708us/step - loss: 0.2375 - accuracy: 0.9116 - val_loss: 0.3471 - val_accuracy: 0.8811
<keras.src.callbacks.History at 0x1541f0f10>
posted @ 2024-07-30 17:56  AI未来10Y  阅读(3)  评论(0编辑  收藏  举报