机器学习实验4:深度学习技术应用 基于TensorFlow

深度学习技术应用

Tips:TensorFlow中文官网有更完整的教程

https://tensorflow.google.cn/tutorials?hl=zh_cn
实验目的

理解深度学习基本原理和概念;

了解 TensorFlow 基本操作;

能够使用 TensorFlow 解决相关问题。

实验内容

使用深度神经网络解决图片分类问题。

实验代码
# 引入必要的模块
from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf

from tensorflow import keras

import numpy as np

import matplotlib.pyplot as plt

# 引入 Fashion MNIST 数据集
fashion_mnist = keras.datasets.fashion_mnist

# 训练集 测试集
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# 图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9 之间。这些标签对应于图像所代表的服装类:

标签	类
0	T恤/上衣
1	裤子
2	套头衫
3	连衣裙
4	外套
5	凉鞋
6	衬衫
7	运动鞋
89	短靴

# 标签 供绘图使用
 class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 探索数据(通过返回结果了解每个语句的作用)

# 训练集中有 60000 个图像,每个图像由 28 x 28 的像素表示
train_images.shape
Out[10]: (60000, 28, 28)

# 标签有60000个
len(train_labels)
Out[11]: 60000

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

# 测试集中有 10,000 个图像。同样,每个图像都由 28x28 个像素表示
test_images.shape
Out[13]: (10000, 28, 28)

# 测试集包含 10,000 个图像标签
len(test_labels)
Out[14]: 10000
    
# 数据预处理 在训练网络之前,必须对数据进行预处理。如果检查训练集中的第一个图像,会看到像素值处于 0 到 255 之间

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

show_image()

# 将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型
train_images = train_images / 255.0

test_images = test_images / 255.0

# 为了验证数据的格式是否正确,以及是否已准备好构建和训练网络,显示训练集中的前 25 个图像,并在每个图像下方显示类名称
def show_first25_images( ):
    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()
        

show_first25_images()

# 建立模型 构建神经网络需要先配置模型的层,然后再编译模型。
# 该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。

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

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

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

# 训练模型
# 训练神经网络模型需要执行以下步骤:
# 1.将训练数据馈送给模型。在本例中,训练数据位于 train_images 和 train_labels 数组中。
# 2.模型学习将图像和标签关联起来。
# 3.要求模型对测试集(在本例中为 test_images 数组)进行预测。
# 4.验证预测是否与 test_labels 数组中的标签相匹配。
# 向模型馈送数据
# 要开始训练,请调用 model.fit 方法,这样命名是因为该方法会将模型与训练数据进行“拟合”
# 在模型训练期间,会显示损失和准确率指标。此模型在训练数据上的准确率达到了 0.89(或 89%)左右。
model.fit(train_images, train_labels, epochs=5)

# 评价模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
313/313 - 0s - loss: 0.3664 - accuracy: 0.8701
# 模型在测试数据集上的准确率略低于训练数据集。
print('测试精度:', test_acc)
测试精度: 0.8701000213623047

# 预测
predictions = model.predict(test_images)

predictions[0]
Out[28]: 
array([5.2492895e-05, 6.3970202e-07, 5.0086419e-06, 4.4656738e-07,
       4.1346425e-06, 2.8909770e-01, 1.7588989e-05, 5.0757393e-02,
       3.5312274e-05, 6.6002923e-01], dtype=float32)

# 预测结果
np.argmax(predictions[0])
Out[29]: 9

# 真实结果
test_labels[0]
Out[30]: 9

# 改进模型:上面 e)中建立的模型 model 是 3 层神经网络,试着增加隐层的层数,然后重新执行 e)- i),看看测试正确率 test_acc 会不会增加)
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

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

Out[33]: <tensorflow.python.keras.callbacks.History at 0x17c5490da30>

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
313/313 - 0s - loss: 0.3780 - accuracy: 0.8643

print('测试精度:', test_acc)
测试精度: 0.864300012588501
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值