目录

Fashion MNIST数据库

分类模型的建立

模型预测

总体代码


主要介绍基于tf.keras的Fashion MNIST数据库分类,

官方文档地址为:https://tensorflow.google.cn/tutorials/keras/basic_classification

文本分类类似,官网文档地址为https://tensorflow.google.cn/tutorials/keras/basic_text_classification

首先是函数的调用,对于tensorflow只有在版本1.2以上的版本才有tf.keras库。另外推荐使用python3,而不是python2。

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras # 其他库
import numpy as np
import matplotlib.pyplot as plt
#查看版本
print(tf.__version__)
#1.9.0

Fashion MNIST数据库

fashion mnist数据库是mnist数据库的一个拓展。目的是取代mnist数据库,类似MINST数据库,fashion mnist数据库为训练集60000张,测试集10000张的28X28大小的服装彩色图片。具体分类如下:

标注编号 描述
0 T-shirt/top(T恤)
1 Trouser(裤子)
2 Pullover(套衫)
3 Dress(裙子)
4 Coat(外套)
5 Sandal(凉鞋)
6 Shirt(汗衫)
7 Sneaker(运动鞋)
8 Bag(包)
9 Ankle boot(踝靴)

样本描述如下:

名称 描述 样本数量 文件大小 链接
train-images-idx3-ubyte.gz 训练集的图像 60,000 26 MBytes 下载
train-labels-idx1-ubyte.gz 训练集的类别标签 60,000 29 KBytes 下载
t10k-images-idx3-ubyte.gz 测试集的图像 10,000 4.3 MBytes 下载
t10k-labels-idx1-ubyte.gz 测试集的类别标签 10,000 5.1 KBytes 下载

单张图像展示代码:

#分类标签
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
#单张图像展示,推荐使用python3
plt.figure()
plt.imshow(train_images[0])
#添加颜色渐变条
plt.colorbar()
#不显示网格线
plt.gca().grid(False)

效果图:

样本的展示代码:

#图像预处理
train_images = train_images / 255.0
test_images = test_images / 255.0 #样本展示
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])

效果图:

分类模型的建立

检测模型输入数据为28X28,1个隐藏层节点数为128,输出类别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=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy', #多分类的对数损失函数
metrics=['accuracy']) #准确度

模型的训练:

model.fit(train_images, train_labels, epochs=5)

模型预测

预测函数:

predictions = model.predict(test_images)

分类器是softmax分类器,输出的结果一个predictions是一个长度为10的数组,数组中每一个数字的值表示其所对应分类的概率值。如下所示:

predictions[0]
array([2.1840347e-07, 1.9169457e-09, 4.5915922e-08, 5.3185740e-08,
6.6372898e-08, 2.6090498e-04, 6.5197796e-06, 4.7861701e-03,
2.9425648e-06, 9.9494308e-01], dtype=float32)

对于predictions[0]其中第10个值最大,则该值对应的分类为class[9]ankle boot。

np.argmax(predictions[0]) #9
test_labels[0] #9

前25张图的分类效果展示:

#前25张图分类效果
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(test_images[i], cmap=plt.cm.binary)
predicted_label = np.argmax(predictions[i])
true_label = test_labels[i]
if predicted_label == true_label:
color = 'green'
else:
color = 'red'
plt.xlabel("{} ({})".format(class_names[predicted_label],
class_names[true_label]),
color=color)

效果图,绿色标签表示分类正确,红色标签表示分类错误:

对于单个图像的预测,需要将图像28X28的输入转换为1X28X28的输入,转换函数为np.expand_dims。函数使用如下:https://www.zhihu.com/question/265545749

#格式转换
img = (np.expand_dims(img,0))
print(img.shape) #1X28X28 predictions = model.predict(img)
prediction = predictions[0]
np.argmax(prediction) #9

总体代码

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras # 其他库
import numpy as np
import matplotlib.pyplot as plt
#查看版本
print(tf.__version__)
#1.9.0 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']
#单张图像展示,推荐使用python3
plt.figure()
plt.imshow(train_images[0])
#添加颜色渐变条
plt.colorbar()
#不显示网格线
plt.gca().grid(False) #图像预处理
train_images = train_images / 255.0
test_images = test_images / 255.0 #样本展示
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]]) #检测模型
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=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy', #多分类的对数损失函数
metrics=['accuracy']) #准确度 model.fit(train_images, train_labels, epochs=5) predictions = model.predict(test_images) #前25张图分类效果
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(test_images[i], cmap=plt.cm.binary)
predicted_label = np.argmax(predictions[i])
true_label = test_labels[i]
if predicted_label == true_label:
color = 'green'
else:
color = 'red'
plt.xlabel("{} ({})".format(class_names[predicted_label],
class_names[true_label]),
color=color) #单个图像检测
img = test_images[0]
print(img.shape) #28X28 #格式转换
img = (np.expand_dims(img,0))
print(img.shape) #1X28X28 predictions = model.predict(img)
prediction = predictions[0]
np.argmax(prediction) #9

[深度学习] tf.keras入门2-分类的更多相关文章

  1. [深度学习] tf.keras入门1-基本函数介绍

    目录 构建一个简单的模型 序贯(Sequential)模型 网络层的构造 模型训练和参数评价 模型训练 模型的训练 tf.data的数据集 模型评估和预测 基本模型的建立 网络层模型 模型子类函数构建 ...

  2. [深度学习] tf.keras入门4-过拟合和欠拟合

    过拟合和欠拟合 简单来说过拟合就是模型训练集精度高,测试集训练精度低:欠拟合则是模型训练集和测试集训练精度都低. 官方文档地址为 https://tensorflow.google.cn/tutori ...

  3. [深度学习] tf.keras入门5-模型保存和载入

    目录 设置 基于checkpoints的模型保存 通过ModelCheckpoint模块来自动保存数据 手动保存权重 整个模型保存 总体代码 模型可以在训练中或者训练完成后保存.具体文档参考:http ...

  4. [深度学习] tf.keras入门3-回归

    目录 波士顿房价数据集 数据集 数据归一化 模型训练和预测 模型建立和训练 模型预测 总结 回归主要基于波士顿房价数据库进行建模,官方文档地址为:https://tensorflow.google.c ...

  5. 深度学习:Keras入门(一)之基础篇

    1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorflow的深度学习框架. Keras是一个高层神经网络API,支持快速实验,能够把你的idea迅速转换为结 ...

  6. 深度学习:Keras入门(一)之基础篇【转】

    本文转载自:http://www.cnblogs.com/lc1217/p/7132364.html 1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorfl ...

  7. 深度学习:Keras入门(一)之基础篇(转)

    转自http://www.cnblogs.com/lc1217/p/7132364.html 1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorflow的深 ...

  8. 深度学习:Keras入门(二)之卷积神经网络(CNN)

    说明:这篇文章需要有一些相关的基础知识,否则看起来可能比较吃力. 1.卷积与神经元 1.1 什么是卷积? 简单来说,卷积(或内积)就是一种先把对应位置相乘然后再把结果相加的运算.(具体含义或者数学公式 ...

  9. 深度学习:Keras入门(二)之卷积神经网络(CNN)【转】

    本文转载自:https://www.cnblogs.com/lc1217/p/7324935.html 说明:这篇文章需要有一些相关的基础知识,否则看起来可能比较吃力. 1.卷积与神经元 1.1 什么 ...

随机推荐

  1. LinkedBlockingQueue详解

    LinkedBlockingQueue介绍 [1]LinkedBlockingQueue是一个基于链表实现的阻塞队列,默认情况下,该阻塞队列的大小为Integer.MAX_VALUE,由于这个数值特别 ...

  2. 跨平台客户端Blazor方案尝试

    一.方案选择 Electron/MAUI + Blazor(AntDesgin blazor) BlazorApp:Blazor Razor页面层,抽象独立层,被BlazorAppElectron/B ...

  3. 『现学现忘』Git分支 — 38、Git分支介绍

    目录 1.Git分支简介 2.Git分支与SVN分支的区别 3.工作中为什么要使用分支 4.Git分支管理的好处 1.Git分支简介 几乎所有的版本控制系统都以某种形式支持分支. 使用分支意味着,你可 ...

  4. JavaScript基础&实战(1)js的基本语法、标识符、数据类型

    文章目录 1.JavaScript简介 2.输出语句 2.1 代码块 2.2 测试结果 3.JS编写位置 3.1代码 3.2 测试结果 4.基本语法 4.1 代码 5.标识符 5.1 代码 6.数据类 ...

  5. Java函数式编程:一、函数式接口,lambda表达式和方法引用

    Java函数式编程 什么是函数式编程 通过整合现有代码来产生新的功能,而不是从零开始编写所有内容,由此我们会得到更加可靠的代码,并获得更高的效率 我们可以这样理解:面向对象编程抽象数据,函数式编程抽象 ...

  6. python同时识别多张人脸(运用face_recognition)

    之前发的博客和网上流传的代码严格来说都只算得上是人脸检测,不能区别人脸,今天来说说真的人脸识别 篇幅所限,就举两张人脸的例子了,本程序需要安装face_recognition 下面是全部源代码: im ...

  7. ES6 学习笔记(二)解构赋值

    一.数组的解构赋值 1.基本用法 ES6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,该操作即为解构 如: let [a,b,c]=[1,2,3]; console.log(a,b,c) ...

  8. 2流高手速成记(之七):基于Dubbo&Nacos的微服务简要实现

    本节内容会用到之前给大家讲过的这两篇: 2流高手速成记(之六):从SpringBoot到SpringCloudAlibaba 2流高手速成记(之三):SpringBoot整合mybatis/mybat ...

  9. 微信小程序的学习(二)

    一.数据绑定 1.数据绑定的基本原则 在 data 中定义数据 在 wxml 中使用数据 2.如何在 data 里面定义数据? 在页面对应的 .js 文件中,把数据定义到 data 对象中即可: 3. ...

  10. 初步探索GraalVM——云原生时代JVM黑科技

    1 云原生时代Java语言的困境 经过多年的演进,Java语言的功能和性能都在不断的发展和提高,诸如即时编译器.垃圾回收器等系统都能体现Java语言的优秀,但是想要享受这些功能带来的提升都需要一段时间 ...