#导入需要的模块
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
#从网络(自动从网络下载)或者本地读取数据集
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
#将图片的标签由数字映射到字符串数组中
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
#检查图片和标签的大小
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels
#检查数据
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
#图像归一化 由整数变为浮点数
train_images = train_images/255
test_images = test_images/255
#显示前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]])
#构建模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28)), #图像由二维数组变为一维数组 (28*28) (28*28=784)
keras.layers.Dense(128,activation=tf.nn.relu), #128个神经元节点的dense层
keras.layers.Dense(10,activation=tf.nn.softmax) #10个输出节点的softmax层
])
#编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
#训练模型
model.fit(train_images, train_labels, epochs=5) #训练5次
#评估准确性
test_loss, test_acc = model.evaluate(test_images,test_labels)
print('test accuracy',test_acc)
#做出预测(输出是一个10个数字的数组,描述模型的“置信度”)
predictions = model.predict(test_images)
#对第一个图像预测
predictions[0]
np.argmax(predictions[0])
test_labels[0]
#定义两个函数
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')
#第一个图像、预测数、预测数组
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)
#第二个突袭、预测数、预测数组
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)
绘制第一个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)
#从测试数据集中获取图像
img = test_images[0]
print(img.shape)
#将图像添加到一个批处理中,其中它是唯一的成员。
img = (np.expand_dims(img,0))
print(img.shape)
predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
p.argmax(predictions_single[0])