TensorFlow的基本使用

本文是按照TensorFlow的官网的教程操作的心得。

https://www.tensorflow.org/tutorials/keras/basic_classification

 

# -*- coding: utf-8 -*-
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


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')

# 导入并加载数据
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']

# 训练集中有60,000个图像,每个图像表示为28 x 28像素
#

train_images = train_images / 255.0  # [0,255]

test_images = test_images / 255.0  # [0,255]

plt.figure(figsize=(10, 10))
for i in range(25):
    plt.subplot(5, 5, i + 1)  # 将图像分成五行五列, i+1代表第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()


# 网络中的第一层, tf.keras.layers.Flatten,
# 将图像格式从一个二维数组(包含着28x28个像素)
# 转换成为一个包含着28 * 28 = 784个像素的一维数组。
# 可以将这个网络层视为它将图像中未堆叠的像素排列在一起。
# 这个网络层没有需要学习的参数;它仅仅对数据进行格式化。

# 在像素被展平之后,网络由一个包含有两个tf.keras.layers.Dense网络层的序列组成。
# 他们被称作稠密链接层或全连接层。 第一个Dense网络层包含有128个节点(或被称为神经元)。
# 第二个(也是最后一个)网络层是一个包含10个节点的softmax层—它将返回包含10个概率分数的数组,总和为1。
# 每个节点包含一个分数,表示当前图像属于10个类别之一的概率。

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方法来训练模型 — 模型对训练数据进行"拟合"。
model.fit(train_images, train_labels, epochs=5)

test_loss, test_acc = model.evaluate(test_images, test_labels)

print('Test accuracy:', test_acc)

predictions = model.predict(test_images)

print(predictions[0])

print(np.argmax(predictions[0]))

print(test_labels[0])

i = 0
plt.figure(figsize=(6, 3))
plt.subplot(1, 2, 1)
# 自定义函数plot_image(i, predictions_array, true_label, img)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1, 2, 2)
# 自定义函数plot_value_array(i, predictions_array, true_label)
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()

# 从测试数据集中获取图像
id = 0
img = test_images[id]

print(img.shape)
print("test_label: ",test_labels[id])
# 将图像添加到批次中,即使它是唯一的成员。
img = (np.expand_dims(img, 0))

print("img.shape: ", img.shape)

predictions_single = model.predict(img)

print(predictions_single)

plot_value_array(id, predictions_single, test_labels)
plt.xticks(range(10), class_names, rotation=45)
plt.show()

prediction_result = np.argmax(predictions_single[0])
print(prediction_result)

这个例子完全是按照教程来做的,你会得到和教程一样的结果,但是中间有一个如果你想要从测试集中随机预测一个种类的话(test_image[?]),那么你需要对这份代码进行稍加修改。

因为案例中的plot_value_array(i, predictions_array, true_label)这个函数,其中i代表了第几个,predictions_array代表了预测的数组,test_labels代表了测试集的标签,又因为在上文的前半部分中传人的predictions_array参数是predictions = model.predict(test_images),其中predictions是所有测试图片的预测数组,所以改变i确实能起到输出第i张测试图片的预测。但是对于后面出现的predictions_single = model.predict(img),要知道的是,在这个当中,img已经不是所有测试集,而是测试图片中的某一张,所以predictions_single代表的是测试图片中的某一张的预测,也就是说是一个由一个一维数组组成的二维数组,所以plot_value_array(0, predictions_single, test_labels)能标注出图片。因为predictions_single[0]就是predictions[i],但是当其中的id改变的时候,predictions_single数组就会越界,所以如果要输出测试图片集中的任意一张的预测的话,应该使用predictions数组,而不是使用predictions_single数组。

而且如果使用plot_value_array(0, predictions_single, test_labels)进行调用的话,会输出这样的一张图片,就是即使预测对了,但是也会输出红色的柱状图,这是因为在这个函数中使用的标准是test_labels[0],而不是我们想要的test_label[i],因此,正确的调用方式为plot_value_array(id, predictions, test_labels),这也才能输出我们想要的图。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值