搭建神经网络进行分类与回归任务

本文展示了如何使用TensorFlow和Keras加载预训练的FashionMNIST模型,对测试数据进行预测,并通过可视化图像和预测概率来理解模型性能。
摘要由CSDN通过智能技术生成

 读取网络模型

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

model = keras.models.load_model('fashion_model.h5')
# 此行从文件“fashion_model.h5”加载预训练的 Keras 模型。
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# 使用 Keras 加载 Fashion MNIST 数据集。它将数据拆分为训练集和测试集,以及相应的图像和标签。

test_images = test_images / 255.0
test_images = tf.expand_dims(test_images, axis=1)
# 将测试图像的像素值归一化为 [0, 1] 范围内。它还为测试图像添加了一个新轴,大概是为了匹配模型预期的输入形状。

predictions = model.predict(test_images)
# 使用加载的模型对预处理的测试图像进行预测。
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([])
    # 通过关闭网格和轴刻度来配置绘图的外观。
    # Reshape the image from (1, 28, 28) to (28, 28)
    img = np.squeeze(img, axis=0)
    # 将图像从 (1, 28, 28) 重塑为 (28, 28)

    plt.imshow(img, cmap='binary')
    # 使用 Matplotlib 的函数显示图像。该参数指示应使用二进制颜色映射表
    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)
#     使用 Matplotlib 的函数将标记文本添加到绘图中。标签包括预测标签、置信百分比和真实标签。颜色是根据预测的正确性确定的。
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))
    # 此线将 x 轴刻度设置为位于位置 0 到 9。它假设有 10 个类。
    plt.yticks([])
    # 此线删除 y 轴刻度。
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    # 此线使用 创建条形图。它表示每个类的预测概率 ()(假设有 10 个类)。条形最初用灰色阴影着色 ()。
    plt.ylim([0, 1])
    # 此线将 y 轴限值设置为介于 0 和 1 之间,假设预测概率在 [0, 1] 范围内。
    predicted_label = np.argmax(predictions_array)
    # 使用 NumPy 的函数来查找 中最大值的索引。此索引表示预测的类。
    thisplot[predicted_label].set_color('red')
    # 此行将与预测类对应的条形颜色设置为红色。
    thisplot[true_label].set_color('blue')
#     此行将与真实类对应的条形的颜色设置为蓝色。

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

#绘制图像和预测数组
num_rows = 5
num_cols = 3
num_images = num_rows * num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
# 本节设置用于在网格中绘制图像的参数。
# 它定义网格中的行数 () 和列数 (),并计算图像总数 ()。
# 然后,它使用 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()

# Normalize train_images and test_images
train_images = train_images / 255.0
test_images = test_images / 255.0

# Make predictions again after normalizing
predictions = model.predict(test_images)

#在归一化后绘制图像和预测数组
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.subplot
# 调用函数并绘制图像及其预测信息
plt.tight_layout()
plt.show()

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值