AI测试 TensorFlow 学习记录 (六:MNIST 数据集显示--tensorflow2)

膨化先生 · 2019年12月24日 · 1425 次阅读

可以和 tensorflow1 对比 TensorFlow 学习记录 (二)

一、访问 MNIST 数据集

TensorFlow 学习记录 (一)中我们知道 MNIST 包括训练集、测试集和验证集。

import tensorflow as tf

mnist = tf.keras.datasets.mnist.load_data(path='mnist.npz')
(keras_train_images, keras_train_labels), (test_images, test_labels) = mnist

# 访问MNIST训练集
train_images=keras_train_images[:-5000]
train_labels=keras_train_labels[:-5000]
print(train_images.shape)
print(train_labels.shape)
# 访问MNIST测试集
print(test_images.shape)
print(test_labels.shape)
# 访问MNIST验证集
validation_images=keras_train_images[-5000:]
validation_labels=keras_train_labels[-5000:]
print(validation_images.shape)
print(validation_labels.shape)

结果是:
(55000, 28, 28)
(55000,)
(10000, 28, 28)
(10000,)
(5000, 28, 28)
(5000,)

keras 没有将训练集划分成训练集和验证集,需要自己将图片划分为 55000 张训练集和 5000 张验证集,测试集仍为 10000 张图片,每张图像表示为 28 x 28 像素。

二、MNIST 图片数组显示

import tensorflow as tf
import numpy as np

mnist = tf.keras.datasets.mnist.load_data(path='mnist.npz')
(keras_train_images, keras_train_labels), (test_images, test_labels) = mnist

# 设置输出结果保留精度为1位小数
np.set_printoptions(precision=1)

train_images=keras_train_images[:-5000]
print(train_images[1, :].reshape(28, 28))

查看数组显示,为方便观看对概率的精度只保留了一位小数:

三、MNIST 图片可视化

from TensorFlow import input_data
import matplotlib.pyplot as plt

mnist = tf.keras.datasets.mnist.load_data(path='mnist.npz')
(keras_train_images, keras_train_labels), (test_images, test_labels) = mnist

# 在将它们输入神经网络模型之前,将这些值缩放到0到1的范围。为此,将值除以255。
keras_train_images = keras_train_images / 255.0

train_images=keras_train_images[:-5000]
train_labels=keras_train_labels[:-5000]
# 获取train_images第二张图片
image = train_images[1]
# 打印train_images[1]对应的标签
print(train_labels[1])

plt.figure()
plt.imshow(image)
plt.show()

使用 plt 库将 MNIST 数据集图片可视化,可以看到图片中显示数字为 0,标签也为 0

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暫無回覆。
需要 登录 後方可回應,如果你還沒有帳號按這裡 注册