第一个神经网络TensorFlow

下面的代码是我操作了一遍tensorflow的helloword教程后,写下的代码。相比教程,多加了些注释,以便更加了解函数的输入输出。
整个代码就是识别鞋子、上衣、裙子、裤子等。安装好tensorflow后就可以马上上手。我用的是spyder写的程序。

**在这里插入图片描述**

1.导入TensorFlow和tf.keras

#----1-------------
from future import absolute_import, division, print_function, unicode_literals

import tensorflow as tf
from tensorflow import keras

#导入辅助库

import numpy as np
import matplotlib.pyplot as plt

print(tf.version)

-------2.导入Fashion MNIST数据集-----------

fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

#由于类别名称不包含在数据集中,因此把他们存储在这里以便在绘制图像时使用:Pullover=套头毛衣; 套衫,Sneaker=运动鞋
class_names = [‘T-shirt/top’, ‘Trouser’, ‘Pullover’, ‘Dress’, ‘Coat’,
‘Sandal’, ‘Shirt’, ‘Sneaker’, ‘Bag’, ‘Ankle boot’]

-------3探索数据

#在训练网络之前必须对数据进行预处理。 如果您检查训练集中的第一个图像,您将看到像素值落在0到255的范围内:
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

#在馈送到神经网络模型之前,我们将这些值缩放到0到1的范围。为此,我们将像素值值除以255。重要的是,对训练集和测试集要以相同的方式进行预处理:
train_images = train_images / 255.0
test_images = test_images / 255.0

#显示训练集中的前25个图像,并在每个图像下方显示类名。验证数据格式是否正确,我们是否已准备好构建和训练网络。
#plt.figure(figsize=(a, b), dpi=dpi).figsize 设置图形的大小,a 为图形的宽, b 为图形的高,单位为英寸
plt.figure(figsize=(10,10))
for i in range(25):
#subplot(m,n,p)是将多个图画到一个平面上的工具。其中,m表示是图排成m行,n表示图排成n列,也就是整个figure中有n个图是排成一行的,一共m行,如果m=2就是表示2行图。p表示图所在的位置,p=1表示从左到右从上到下的第一个位置。
plt.subplot(5,5,i+1)
# 显示x轴的刻标,不想显示ticks则可以可以传入空的参数
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()

-------4构建模型

#Relu激活函数(The Rectified Linear Unit)表达式为:f(x)=max(0,x)。
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)
])

model.compile(optimizer=‘adam’,
loss=‘sparse_categorical_crossentropy’,
metrics=[‘accuracy’])
#训练模型
model.fit(train_images, train_labels, epochs=5)

#评估准确率
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(‘Test accuracy:’, test_acc)

--------5.模型结果

#通过训练模型,我们可以使用它来预测某些图像。
predictions = model.predict(test_images)
#print(‘predictions[0]’,predictions[0])
np.argmax(predictions[0])

#正确的预测标签是蓝色的,不正确的预测标签是红色的。该数字给出了预测标签的百分比(满分100)。请注意,即使非常自信,也可能出错
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
print(‘predictions[0]’,predictions[i])
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()

i = 12
print(‘predictions[12]’,predictions[i])
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_rowsnum_cols
plt.figure(figsize=(2
2num_cols, 2num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2num_cols, 2i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2num_cols, 2i+2)
plot_value_array(i, predictions, test_labels)
plt.show()

发布了21 篇原创文章 · 获赞 18 · 访问量 1471

猜你喜欢

转载自blog.csdn.net/zephyr_wang/article/details/101701259