tensorflow基本图像分类

基本图像分类

  • 处理步骤
    • 预处理数据
    • 构建模型
    • 设置层
    • 编译模型
    • 训练模型
      • 向模型馈送数据
    • 评估准确率
    • 进行预测
  • 相关代码

  1. tensorflow 版本 version 2.3.1
  2. Fashion MNIST 数据集,该数据集包含 10 个类别的 70,000 个灰度图像。这些图像以低分辨率(28x28 像素)展示了单件衣物,Fashion MNIST 旨在临时替代经典 MNIST 数据集,常被用作计算机视觉机器学习程序的“Hello, World”
  3. 图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9 之间。这些标签对应于图像所代表的服装类:
标签 说明
0 T恤/上衣 T-shirt/top
1 裤子 Trouser
2 套头衫 Pullover
3 连衣裙 Dress
4 外套 Coat
5 凉鞋 Sandal
6 衬衫 Shirt
7 运动鞋 Sneaker
8 Bag
9 短靴 Ankle boot

处理步骤

预处理数据

将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,请将这些值除以 255。请务必以相同的方式对训练集和测试集进行预处理:

构建模型

构建神经网络需要先配置模型的层,然后再编译模型

设置层

神经网络的基本组成部分是层。层会从向其馈送的数据中提取表示形式。希望这些表示形式有助于解决手头上的问题。
大多数深度学习都包括将简单的层链接在一起。大多数层(如 tf.keras.layers.Dense)都具有在训练期间才会学习的参数。

该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。

展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。

编译模型

在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的

  1. 损失函数 - 用于测量模型在训练期间的准确率。您会希望最小化此函数,以便将模型“引导”到正确的方向上。
  2. 优化器 - 决定模型如何根据其看到的数据和自身的损失函数进行更新。
  3. 指标 - 用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。

训练模型

训练神经网络模型需要执行以下步骤:
1.将训练数据馈送给模型。在本例中,训练数据位于 train_images 和 train_labels 数组中。
2. 模型学习将图像和标签关联起来。
3. 要求模型对测试集(在本例中为 test_images 数组)进行预测。
4. 验证预测是否与 test_labels 数组中的标签相匹配。

向模型馈送数据

要开始训练,请调用 model.fit 方法,这样命名是因为该方法会将模型与训练数据进行“拟合”:

评估准确率

进行预测

在模型经过训练后,您可以使用它对一些图像进行预测。模型具有线性输出,即 logits。您可以附加一个 softmax 层,将 logits 转换成更容易理解的概率。

相关代码

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 16:30:52 2020

@author: Administrator
"""
import tensorflow as tf

print('#本指南将训练一个神经网络模型,对运动鞋和衬衫等服装图像进行分类!')
# 使用了 tf.keras,它是 TensorFlow 中用来构建和训练模型的高级 API
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print("#tensorflow version:", tf.__version__)  # 2.3.1

# 数据集
print("#Fashion MNIST 数据集,该数据集包含 10 个类别的 70,000 个灰度图像。这些图像以低分辨率(28x28 像素)展示了单件衣物")
print("#Fashion MNIST 旨在临时替代经典 MNIST 数据集,常被用作计算机视觉机器学习程序的“Hello, World”")
print("#MNIST 数据集包含手写数字(0、1、2 等)的图像,其格式与您将使用的衣物图像的格式相同")
print("#这两个数据集都相对较小,都用于验证某个算法是否按预期工作。对于代码的测试和调试,它们都是很好的起点")

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# train_images 和 train_labels 数组是训练集,即模型用于学习的数据
# 测试集、test_images 和 test_labels 数组会被用来对模型进行测试
#

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

print('#训练集:', train_images.shape)
print("#标签长度:", len(train_labels))
print("#标签:", train_labels)
print("#测试集:", test_images.shape)
print("#测试集标签长度:", len(test_labels))

print("#1.预处理数据...")
plt.figure()
plt.imshow(train_images[200])
plt.colorbar()
plt.grid(False)
plt.show()  # 可以在 Plots 面板中看到图像
# 将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,请将这些值除以 255。请务必以相同的方式对训练集和测试集进行预处理:
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()

print("#2.构建模型")
print("# 2.1 设置层")
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),  ## 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)
    keras.layers.Dense(128, activation='relu'),  ## 密集连接或全连接神经层 128 个节点(或神经元)
    keras.layers.Dense(10)  ## 长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类
])
print("#3.编译模型")
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

print('#4.向模型馈送数据 ')
model.fit(train_images, train_labels, epochs=10)
print("#5.评估准确率")
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

print('#6 进行预测')
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print("预测第一个结果:", predictions[0])
print("可信度最大值:", np.argmax(predictions[0]))


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')


print("验证预测结果:")
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()

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()

# 使用训练好的模型对单个图像进行预测
img = test_images[1]
print(img.shape)

# tf.keras 模型经过了优化,可同时对一个批或一组样本进行预测
img = (np.expand_dims(img, 0))
print(img.shape)

# 增加相应标签
 
predictions_single = probability_model.predict(img)
print(predictions_single)
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
 


源自:tensorflow

你可能感兴趣的:(机械学习,tensorflow,图像分类)