Tensorflow学习(三)---对服装图像进行分类

 原文链接

https://tensorflow.google.cn/tutorials/keras/classification

from __future__ import absolute_import, division, print_function, unicode_literals
# from __future__ import function
# 当识别到from future import xxx这样的声明后,编译器会生成一些为了适应future特性与原版不同的代码,但同时也可能引起新的不兼容问题,意味着即使代码不兼容也可以使用新的特性。

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
fashion_mnist = keras.datasets.fashion_mnist

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

# 下载数据集
# 使用60,000张图像来训练网络,使用10,000张图像来评估网络学习对图像进行分类的准确程度。您可以直接从TensorFlow访问Fashion MNIST。直接从TensorFlow导入和加载Fashion MNIST数据
标签
0T恤/上衣
1个裤子
2拉过来
3连衣裙
4涂层
5凉鞋
6衬衫
7运动鞋
8
9脚踝靴
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# 定义标签名

 

train_images.shape

(60000,28,28)
# 训练集中有60,000张图像,每张图像表示为28 x 28像素

train_labels

array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
# 每个标签都是0到9之间的整数

test_images.shape

(10000, 28, 28)
# 测试集中有10,000张图像。同样,每个图像都表示为28 x 28像素

预处理数据

在训练网络之前,必须对数据进行预处理。如果检查训练集中的第一张图像,您将看到像素值落在0到255的范围内:

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

 

train_images = train_images / 255.0

test_images = test_images / 255.0

# 在将它们输入神经网络模型之前,将这些值缩放到0到1的范围。为此,将值除以255。
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1) # 5行5列,注意,第一张图从1开始,所以必须是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()
# 我们显示训练集中的前25张图像,并在每个图像下方显示类别名称。

建立模型

建立神经网络需要配置模型的各层,然后编译模型。

设置图层

神经网络的基本组成部分是。图层从输入到其中的数据中提取表示。希望这些表示对于当前的问题有意义。

深度学习的大部分内容是将简单的层链接在一起。大多数层(例如tf.keras.layers.Dense)具有在训练期间学习的参数。

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])
# Keras提供的模型,其中分为两类:
# Sequential 顺序模型,层(layers)的线性堆栈。简单来说,它是一个简单的线性结构,没有多余分支,是多个网络层的堆叠。
# Model 类模型,是带有函数API的,不是线性的,它是一个可以多输入、多输出的模型。


# 首先通过Flatten将输入展平,输入为(28*28)二维数组转为一维28*28=784
# 第一个全连接层(Dense),以尺寸为784的一维数组作为输入,激活函数是relu,输出是(*,128)
# 第二个全连接层(Dense),以尺寸为784的一维数组作为输入,激活函数是softmax,输出是(*,10)

该网络的第一层tf.keras.layers.Flatten将图像的格式从二维数组(28 x 28像素)转换为一维数组(28 * 28 = 784像素)。可以将这一层看作是堆叠图像中的像素行并对齐它们。该层没有学习参数。它只会重新格式化数据。

像素变平后,网络由tf.keras.layers.Dense两层序列组成。

这些是紧密连接或完全连接的神经层。

第一Dense层有128个节点(或神经元)。

第二层(也是最后一层)是一个10节点的softmax层,该层返回10个总和为1的概率分数的数组。每个节点都包含一个分数,该分数指示当前图像属于10个类别之一的概率。

 

编译模型

在准备训练模型之前,需要进行一些其他设置。这些是在模型的编译步骤中添加的:

  • 损失函数 -衡量训练期间模型的准确性。您希望最小化此功能,以在正确的方向上“引导”模型。
  • 优化器 -这是基于模型看到的数据及其损失函数来更新模型的方式。
  • 指标 -用于监视培训和测试步骤。以下示例使用precision,即正确分类的图像比例。 
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 优化器adam

训练模型

训练神经网络模型需要执行以下步骤:

  1. 将训练数据输入模型。在此示例中,训练数据在train_imagestrain_labels数组中。
  2. 该模型学习关联图像和标签。
  3. 您要求模型对测试集(在本例中为test_images数组)做出预测。验证预测是否与test_labels阵列中的标签匹配。

要开始训练,请调用该model.fit方法,之所以这么称呼是因为该方法使模型“适合”训练数据:

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

评估准确性

接下来,比较模型在测试数据集上的表现:

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

print('\nTest accuracy:', test_acc)

作出预测 

通过训练模型,您可以使用它来预测某些图像。

predictions = model.predict(test_images)

在这里,模型已经预测了测试集中每个图像的标签。让我们看一下第一个预测:

predictions[0]

 

array([1.06123218e-06, 8.76374884e-09, 4.13958730e-07, 9.93547733e-09,
       2.39135318e-07, 2.61428091e-03, 2.91701099e-07, 6.94991834e-03,
       1.02351805e-07, 9.90433693e-01], dtype=float32)

预测是由10个数字组成的数组。它们代表模型对图像对应于10种不同服装中的每一种的“信心”。您可以看到哪个标签的置信度最高:

np.argmax(predictions[0])

9

检查真实的标签

test_labels[0]

9
def plot_image(i, predictions_array, true_label, img):
    predictions_array, true_label, img = predictions_array, 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):
    predictions_array, true_label = predictions_array, 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')

# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
    plt.subplot(num_rows, 2*num_cols, 2*i+1)
    plot_image(i, predictions[i], test_labels, test_images)
    plt.subplot(num_rows, 2*num_cols, 2*i+2)
    plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

 

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值