Tensorflow 入门级Hellow World (basic classification)

上一篇帖子:ubuntu16.04使用Anaconda3安装Tensorflow

本篇,按照Google TensorFlow 教程实现Basic Classification Demo.原文链接:

https://www.tensorflow.org/tutorials/keras/basic_classification#Preprocess%20the%20data

1.查看env环境列表

conda env list

2.切换到venv虚拟环境(venv是在上一篇帖子中创建的带tensorflow pip包的环境)

source activate venv

3.创建py文件(我这里命名为basic_classification.py)

touch basic_classification.py

4.编写代码,Basic Classification Demo主要分为五打步骤,分别是:导入数据集、预处理数据、构建模型、训练模型、评估准确性、作出预测。

  • 导入数据集(包括:60000张训练的图片数据和对应的标签,10000测试的图片数据和对应的标签)
#load train and test dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
  • 预处理数据
#preprocess data
train_images, test_images = train_images / 255.0, test_images / 255.0
  • 构建模型 (包括设置layers,编译模型)
#setup the layers
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)
])

#compile the model
model.compile(optimizer=tf.train.AdamOptimizer(), 
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
  • 训练模型
#train the model
model.fit(train_images, train_labels, epochs=5)
  • 评估准确性
#evalute accuracy
test_loss, test_acc = model.evaluate(test_images, test_labels)

print('Test accuracy:', test_acc)
  • 作出预测
# make predictions
predictions = model.predict(test_images)

Demo 完整代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

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

#load train and test dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

#preprocess data
train_images, test_images = train_images / 255.0, test_images / 255.0

#setup the layers
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)
])

#compile the model
model.compile(optimizer=tf.train.AdamOptimizer(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

#train the model
model.fit(train_images, train_labels, epochs=5)

#evaluate accuracy
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

#make predictions
predictions = model.predict(test_images)

#show predictions
num_rows, num_cols = 5, 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)
  if(num_images - i <= 3):
    _ = plt.xticks(range(10), class_names, rotation=90)
plt.show()

运行结果: 

Tensorflow 入门级Hellow World (basic classification)_第1张图片

 

 

 

你可能感兴趣的:(Tensorflow 入门级Hellow World (basic classification))