import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
#Fashion MNIST 数据集包含10个类别的70000个灰度图像,这些图像以低分辨率(28*28像素)展示了单件衣物
#使用 60,000 个图像来训练网络,使用 10,000 个图像来评估网络学习对图像分类的准确率
(train_images,train_labels),(test_images,test_labels) = keras.datasets.fashion_mnist.load_data()
#train_images 和 train_labels 数组是训练集,即模型用于学习的数据。
#测试集、test_images 和 test_labels 数组会被用来对模型进行测试。
#图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9 之间。
#0:T恤 1:裤子 2:套头衫 3:连衣裙 4:外套 5:凉鞋 6:衬衫 7:运动鞋 8:包 9:短靴
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# print(train_images.shape)
# print(len(train_labels))
# plt.figure()
# plt.imshow(train_images[0])
# plt.colorbar()
# plt.grid(False)
# plt.show()
#在训练网络之前,必须对数据进行预处理。如果您检查训练集中的第一个图像,您会看到像素值处于 0 到 255 之间
#将这些值缩小至 0 到 1 之间,将这些值除以 255,然后将其馈送到神经网络模型。
train_images = train_images/255.0
test_images = test_images/255.0
# 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()
#设置层
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
# 该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。
# 将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。
# 展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。
# 第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 的 logits 数组。
# 每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。
#编译模型
model.compile(
optimizer='adam',
loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
#训练模型
# 将训练数据馈送给模型。在本例中,训练数据位于 train_images 和 train_labels 数组中。
# 模型学习将图像和标签关联起来。
# 要求模型对测试集(在本例中为 test_images 数组)进行预测。
# 验证预测是否与 test_labels 数组中的标签相匹配。
model.fit(train_images,train_labels,epochs=5)
#
# test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
# print('\nTest accuracy:', test_acc)
probability_model = keras.Sequential([model, keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
# print(predictions[0])
# print(np.argmax(predictions[0]))
# print(test_labels[0])
def plot_image(i, prediction_array, true_label, img):
prediction_array, true_label, img = prediction_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
prediction_label = np.argmax(prediction_array)
if prediction_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[prediction_label],
100*np.max(prediction_array),
class_names[true_label]),
color=color)
def plot_value_array(i, prediction_array, true_label):
prediction_array,true_label = prediction_array,true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), prediction_array, color="#777777")
plt.ylim([0,1])
prediction_label = np.argmax(prediction_array)
thisplot[prediction_label].set_color('red')
thisplot[true_label].set_color('blue')
# i = 0
# 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()
# 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()
#使用训练好的模型
plt.figure(figsize=(6,3))
img = test_images[1]
print(img.shape)
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)
print(np.argmax(predictions_single[0]))
plt.show()
TensorFlow2.3.1对Fashion MNIST数据集相关训练
最新推荐文章于 2022-07-09 17:32:17 发布