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

运行结果: 

 

 

 

在编程的世界里,"Hello, World!" 是经典的第一个程序示例,通常用于演示如何启动并运行一个新的代码环境。然而,编程涵盖了许多其他主题和概念。 如果你想要了解除 "Hello, World!" 之外的内容,这里有几个关键点: 1. 数据类型和变量:不同编程语言支持各种数据类型(如整数、浮点数、字符串等),以及如何声明和操作这些变量。 2. 控制结构:包括条件语句(if-else)、循环(for、while)、分支(switch-case)等,用于控制程序的流程。 3. 函数和方法:组织可重用代码的方式,定义输入和输出,并提高代码的模块化。 4. 数组和容器:存储一组相同或不同类型的数据集合,如数组、列表、字典或集合。 5. 基础数据结构:如栈、队列、链表、树和图,它们是算法和数据处理的基础。 6. 面向对象编程 (OOP):概念如类、对象、继承、封装和多态,这些都是许多现代软件架构的核心。 7. 进程和线程:理解和管理并发执行的多个任务或指令。 8. 异常处理:处理程序运行过程中的错误和异常情况,提供优雅的恢复机制。 9. 输入/输出 (I/O):处理程序与用户交互,读取文件,网络通信等。 10. 版本控制:像 Git 这样的工具,用于跟踪和管理代码的历史更改。 每个程序员都需要逐步学习这些内容,并通过实践不断巩固技能。如果你对某个特定领域感兴趣,比如 web 开发、移动应用、游戏开发或数据分析,请告诉我,我可以深入讲解相关的知识点。如果你对某个具体的问题感到困惑,也随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值