Tensorflow工具包(一):最简神经网络 keras MNIST测试代码:基础服装分类 - tf中的hello world

根据Tensorflow官网叙述,keras中的MNIST服装分类相当于tensorflow中的【hello world】,是一个良好的测试Tensorflow环境的工具。

新装的最新版1.13.1当然是要先测试一下在撸起袖子干啦!

以下摘自Tensorflow官网:
https://www.tensorflow.org/tutorials/keras/basic_classification

Fashion MNIST 的作用是成为经典 MNIST 数据集的简易替换,后者通常用作计算机视觉机器学习程序的“Hello, World”入门数据集。MNIST 数据集包含手写数字(0、1、2 等)的图像,这些图像的格式与我们在本教程中使用的服饰图像的格式相同。

本指南使用 Fashion MNIST 实现多样化,并且它比常规 MNIST 更具挑战性。这两个数据集都相对较小,用于验证某个算法能否如期正常运行。它们都是测试和调试代码的良好起点。

我们将使用 60000 张图像训练网络,并使用 10000 张图像评估经过学习的网络分类图像的准确率。您可以从 TensorFlow 直接访问 Fashion MNIST。

代码附上
由于博主留学,跟教研室交流方便,懒得翻译,注释就用英文啦。

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

# Show single picture
def mnist_show_pic(num):
    plt.figure()
    plt.imshow(train_images[num])
    plt.colorbar()
    plt.grid(False)
    plt.show()

# show pictures with labels in an array
# num_img : number of first pictures to show
# num_x : number of pictures in x-dir of the array
# num_y : number of pictures in y-dir of the array
def mnist_show_label(num_img, num_x, num_y):
    plt.figure(figsize=(10,10))
    for i in range(num_img):
        plt.subplot(num_x, num_y, 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()

# plot single image with predictions
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)

# plot images with predictions in array
def plot_value_array(i, predictions_array, true_label, num_classes, class_names):
      predictions_array, true_label = predictions_array[i], true_label[i]
      plt.grid(False)
      plt.xticks(np.arange(num_classes), [str(j) for j in np.arange(num_classes)])
      plt.yticks()
      thisplot = plt.bar(range(num_classes), 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')


# Output results for one image
def plot_result(num):
    plt.figure(figsize=(6,3))
    # Subplot 1: image with prediction and ground truth:
    # <prediction> <probability> (<ground_truth>)
    plt.subplot(1,2,1)
    plot_image(num, predictions, test_labels, test_images)
    # Subplot 2: image with prediction and ground truth:
    # <prediction> <probability> (<ground_truth>)
    plt.subplot(1,2,2)
    plot_value_array(num, predictions, test_labels, num_classes, class_names)
    plt.show()

# Output num_rows*num_cols results for image array
def plot_result_array(num_rows, num_cols):
    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, num_classes, class_names)
    plt.show()

"""
==============================================================================
Main
==============================================================================
"""

if __name__ == '__main__':
    
    # Load fashion_mnist database
    # 60000 training images and labels
    # 10000 test images and labels
    fashion_mnist = keras.datasets.fashion_mnist
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
    
    # Class names
    class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
                   'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    num_classes = len(class_names)
    
    # Scale pixel values to 0~1
    train_images = train_images / 255.0
    test_images = test_images / 255.0
    
    # Show pictures (test)
    # mnist_show_pic(8)
    # mnist_show_label(9, 3, 3)
    
    # Setup layers
    # Flatten-fc128relu-fc10softmax
    model = keras.Sequential([
            # Stretch 28*28 image to 748*1 flattened vector
            keras.layers.Flatten(input_shape=(28,28)),
            # Fully-connected layer with 128 neurons, relu
            keras.layers.Dense(128, activation=tf.nn.relu),
            # Fully-connected layer with 10 neurons, softmax
            keras.layers.Dense(10, activation=tf.nn.softmax) 
    ])
    
    # Compile model
    # Loss function: to steer the model in the right direction
    # Optimizer: the way to update model based on losses
    # Metrics: monitor the training and testing steps
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    # Train model with 5 epochs
    model.fit(train_images, train_labels, epochs=5)
    
    # Evaluate model
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print("\nFinally:\ntest_loss=%.4f, test_acc=%.4f" % (test_loss, test_acc))
    
    # Make predictions
    predictions = model.predict(test_images)
    
    # Show prediction confidence (probability) array of first picture
    # predictions[0]
    
    # Return the predicted class
    # class_names[np.argmax(predictions[0])]
    
    # Plot result for single image
    plot_result(3)   # result of image no.3
    plot_result_array(3,4)   # result of first 12 images in array 3*4

运行结果:
输出每次epoch的准确度:

Epoch 1/5
2019-03-06 18:41:25.739511: I tensorflow/stream_executor/dso_loader.cc:152] successfully opened CUDA library libcublas.so.10.0 locally
60000/60000 [==============================] - 4s 67us/sample - loss: 0.5017 - acc: 0.8220
Epoch 2/5
60000/60000 [==============================] - 2s 40us/sample - loss: 0.3773 - acc: 0.8635
Epoch 3/5
60000/60000 [==============================] - 2s 39us/sample - loss: 0.3373 - acc: 0.8771
Epoch 4/5
60000/60000 [==============================] - 2s 39us/sample - loss: 0.3140 - acc: 0.8845
Epoch 5/5
60000/60000 [==============================] - 2s 39us/sample - loss: 0.2943 - acc: 0.8924
10000/10000 [==============================] - 0s 22us/sample - loss: 0.3398 - acc: 0.8793

Finally:
test_loss=0.3398, test_acc=0.8793

输出了图片、标签、以及softmax输出(可以理解为“概率”)
图片3:长裤,分类正确,“confidence level”为100%
在这里插入图片描述
前12张图的结果汇总:其中Sandal的分类错误
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值