tensorflow2.2基本服装图像fashion_mnist分类

采用FashionMNIST 数据集

首先查看TensorFlow版本,代码:

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

结果:

2.2.0

导入Fashion MNIST 数据集

fashion_mnist = keras.datasets.fashion_mnist

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

此数据集是28 x 28Numpy数组,通道数为1,黑白图片,像素范围是0到255。标签是整数数组,范围是0到9
在这里插入图片描述
每个图像都映射到一个标签。由于类名不包含在数据集中,因此将它们存储在此处以供以后在绘制图像时使用:

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

我们可以看看数据集的格式。

train_images.shape
(60000, 28, 28)

训练数据集有60000张图片,每张像素为28 x 28。
同样训练集为:

train_labels.shape
(60000,)

测试集的shape为:

test_labels.shape
(10000,)

先查看一下训练集中的一张图像看看:

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

在这里插入图片描述
对这些值做归一化处理,把值放缩到0-1之间

train_images = train_images / 255.0

test_images = test_images / 255.0

查看训练集中前25张图像,并显示名称:

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

在这里插入图片描述

建立神经网络模型

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(256, activation='relu'),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(10)
])

第一层将图像从二维数组(28,28)转换为一维数组(784,)像素平展处理。
后面两层是128个节点,10个节点。

2021年5月19日更新,使用卷积神经网络模型

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

fashion_mnist = 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

train_images = tf.reshape(train_images, [-1, 28, 28, 1])
test_images = tf.reshape(test_images, [-1, 28, 28, 1])

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# model = keras.Sequential([
#     keras.layers.Flatten(input_shape=(28, 28)),
#     keras.layers.Dense(128, activation='relu'),
#     keras.layers.Dense(10)
# ])

model = keras.Sequential([
    keras.layers.Conv2D(32, kernel_size=[3, 3], padding="same", activation='relu', input_shape=(28, 28, 1)),
    keras.layers.MaxPooling2D(2, 2),
    keras.layers.Dropout(0.5),

    keras.layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation='relu'),
    keras.layers.MaxPooling2D(2, 2),
    keras.layers.Dropout(0.5),

    keras.layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation='relu'),

    keras.layers.Flatten(),

    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dropout(0.5),

    keras.layers.Dense(10)
])

model.summary()

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

'''
fit 中的 verbose

verbose:日志显示
verbose = 0 为不在标准输出流输出日志信息
verbose = 1 为输出进度条记录
verbose = 2 为每个epoch输出一行记录
注意: 默认为 1
'''
model.fit(train_images, train_labels, epochs=10)

'''
evaluate 中的 verbose
verbose:日志显示
verbose = 0 为不在标准输出流输出日志信息
verbose = 1 为输出进度条记录
注意: 只能取 0 和 1;默认为 1
'''
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

结果:

Epoch 10/10
1875/1875 [==============================] - 7s 3ms/step - loss: 0.2989 - accuracy: 0.8901
313/313 - 1s - loss: 0.2491 - accuracy: 0.9091

Test accuracy: 0.9090999960899353

编译模型

模型搭建完成后,需要编译,设置一些参数:
损失函数 :衡量训练期间模型的准确性。您希望最小化此功能,以在正确的方向上“引导”模型。
优化器 :这是基于模型看到的数据及其损失函数来更新模型的方式。
指标 :用于监视培训和测试步骤。以下示例使用precision,即正确分类的图像比例。

'''
如果你的 targets 是 one-hot 编码,用 categorical_crossentropy
  one-hot 编码:[0, 0, 1], [1, 0, 0], [0, 1, 0]
如果你的 tagets 是 数字编码 ,用 sparse_categorical_crossentropy
  数字编码:2, 0, 1
'''
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

训练模型

训练神经网络模型需要执行以下步骤:
1、将训练数据输入模型;
2、模型学习图像和相对应的标签;
3、模型对测试集进行预测;
4、验证模型。

给数据

model.fit(train_images, train_labels, epochs=15)
Epoch 14/15
1875/1875 [==============================] - 4s 2ms/step - loss: 0.2662 - accuracy: 0.9001
Epoch 15/15
1875/1875 [==============================] - 4s 2ms/step - loss: 0.2605 - accuracy: 0.9024

训练时精度为0.9024

评估性能

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

print('Test loss:', test_loss)
print('Test accuracy:', test_acc)
313/313 - 0s - loss: 0.3257 - accuracy: 0.8866
Test loss: 0.3256571888923645
Test accuracy: 0.8866000175476074

事实证明,测试数据集的准确性略低于训练数据集的准确性。
过度拟合的模型“记忆”训练数据集中的噪声和细节,从而对新数据的模型性能产生负面影响。

验证预测

以图像方式查看完整的10个类预测

probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)


def plot_image(i, predictions_array, true_label, img):
    true_label, img = true_label[i], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(img, cmap=plt.cm.binary)

    predicted_label = np.argmax(predictions_array)
    if predicted_label == true_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                         100*np.max(predictions_array),
                                         class_names[true_label]),
               color=color)


def plot_value_array(i, predictions_array, true_label):
    true_label = true_label[i]
    plt.grid(False)
    plt.xticks(range(10))
    plt.yticks([])
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)

    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('blue')

通过训练模型,可以使用它来预测某些图像。
正确的预测标签为蓝色,错误的预测标签为红色。

i = 1
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

在这里插入图片描述

i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

在这里插入图片描述

它预测的是55%是运动鞋,45%是凉鞋,所以模型不是100%有效,毕竟我们人眼对这一张图片也分辨的不好。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值