tensorflow学习——(fashion_mnist数据集)基本分类first_1.py——2

1.导入模块,统一编码
2.导入tensorflow和tf.keras
3.导入辅助库
4.导入fashion_mnist数据集
5.探索数据
6.数据预处理
7.构建模型,设置网络层
8.编译模型(损失函数、优化器、评价方式)
9.训练模型
10.评估模型
11.预测
12.图像显示

1.导入模块统一编码

from __future__ import absolute_import, division, print_function, unicode_literals

2.导入tensorflow和tf.keras

import tensorflow as tf
from tensorflow import keras

3.导入辅助库

import numpy as np
import matplotlib.pyplot as plt

4.导入fashion_mnist数据集

fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
#此处返回四个Numpy数组:train_images,train_labels,test_images,test_labels
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

5.探索数据

#共有6000个图像,每个图像表示为28*28像素 (6000,28,28)
print("train_images.shape",train_images.shape)
#训练集中有6000个标签
print("len(train_labels)",len(train_labels))
#每个标签都死0到9之间的整数
print("train_labels",train_labels)
#测试集中有10000个图像,同样,每个图像表示为28*28像素
print("test_images.shape",test_images.shape)
#测试集包含10000个标签
print("len(test_labels)",len(test_labels))

6.数据预处理

#显示训练集中第一个图片,像素值落到0到255范围内
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
#在馈送到神经网络之前,要将这些值缩放到0到1之间,故将像素值除以255.0
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()

7.构建模型

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

'''设置网络层'''
# =============================================================================
# 网络层是神经网络最基本的组成部分,网络层从提供给它的数据中提取表示。
# 大多数深度学习是由串联在一起的网络层所组成。大多数网络层,
# 例如tf.keras.layers.Dense,具有在训练期间学习的参数。
# =============================================================================

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)
])
# =============================================================================
# 1.网络中的第一层keras.layers.Faltten,将图像格式从一个二维数组(包含28*28个像素),
# 转换为一个28*28=784的一维数组,可以将这个网络层视为将图像中未堆叠在一起的像素
# 排列在一起。这个网络层中没有学习的参数,仅仅对数据进行格式化。
# 2.像素展平之后,网络层由一个包含两个keras.layers.Dense网络层的序列组成,
# 他们被称作稠密连接层或全连接层。
#   2.1第一个Dense网络层包含128个节点(神经元)
#   2.2第二个Dense网络层是是一个包含10个节点的softmax层,它将返回包含10个概率分数的数组,
# 总和为1。每个节点包含一个分数,表示当前图像属于10个类别之一的概率。
# =============================================================================

8.编译模型

# =============================================================================
# 在模型准备好,进行训练之前,还要进行一些配置,
# 1.损失函数:衡量模型在训练过程中的准确程度。我们希望将此函数最小化以“驱使”模型
# 朝正确的方向拟合。
# 2.优化器:这就是模型根据它所看到的数据和损失函数进行更新的方式。
# 3.评价方式:用于监控训练和测试步骤,以下示例使用准确率(accuracy),
# 即正确分类的图像的分数。
# =============================================================================
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

9.训练模型

#使用model.fit函数来训练模型
model.fit(train_images, train_labels, epochs=5)

10.评估模型

#评估模型在测试集上的准确率
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

11.预测

#对测试集图像进行预测
predictions = model.predict(test_images)
#输出测试机第一个图像的预测结果,预测是10个分数,对应10种类别
print('predictions[0]:',predictions[0])
#输出具有最高置信度的标签:9
print('np.argmax(predictions[0]):',np.argmax(predictions[0]))
#检查预测标签是否正确:9
print('test_labels[0]:',test_labels[0])

12.图像预测结果和显示

#用图表来查看全部10个类别
def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], 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[i], true_label[i]
  plt.grid(False)
  plt.xticks([])
  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')

#显示第0个图象,预测和预测数组
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)
plt.show()

#显示第12个图象,预测和预测数组
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)
plt.show()

# 绘制前X个测试图像,预测标签和真实标签
# 以蓝色显示正确的预测,红色显示不正确的预测
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, test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions, test_labels)
plt.show()

#对训练集中的单个图像进行预测
# 从测试数据集中获取图像
img = test_images[0]

print(img.shape)

#tf.keras模型经过优化,可以一次性对批量,或者一个集合的数据进行预测。
# 将图像添加到批次中,即使它是唯一的成员。
img = (np.expand_dims(img,0))
#(1,28,28)
print(img.shape)
#单个图像的预测
predictions_single = model.predict(img)

print(predictions_single)

prediction_result = np.argmax(predictions_single[0])
print(prediction_result)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值