tensorflow文档教程(tensorflow与pytorch的区别)

文章学习资源来自TensorFlow官网文档

一、 说明

本文训练一个网络模型来进行服装分类,比如衣服是T恤还是夹克。这可以快速入门了解TensorFlow2.0怎么进行分类任务的。

二、步骤

1. 引入 tf.keras

from __future__ import absolute_import, division, print_function, unicode_literals# TensorFlow and tf.kerasimport tensorflow as tffrom tensorflow import keras# Helper librariesimport numpy as npimport matplotlib.pyplot as pltprint(tf.__version__)

2. 导入MNIST时装数据集

Fashion MNIST 包含了10类、70000张灰度图。这个数据集被打造为图像识别任务的Hello World程序。数据集地址 :https://github.com/zalandoresearch/fashion-mnist下面图片是一些图片示例(28*28像素):

tensorflow文档教程(tensorflow与pytorch的区别)

加载的数据集返回4个NumPy数组:

  • train_images , train_labels 数组:模型数据训练集
  • test_images,test_labes 数组:模型测试集

图像是28*28的NumPy数组,像素值从0-255。标是整数,0-9,下面是含义:

LabelClass0T-shirt/top1Trouser2Pullover3Dress4Coat5Sandal6Shirt7Sneaker8Bag9Ankle boot

下面定义标注名称:

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

3. 分析数据

通过train_images.shape可以查看训练模型的数据格式,这里会显示它是60000张图片的训练集,每个图片28*28像素:

tensorflow文档教程(tensorflow与pytorch的区别)

类似的,也可以查看测试集。

4. 预处理数据

训练前要先把数据预处理。这里可以先试着看一张图片:

plt.figure()plt.imshow(train_images[0])plt.colorbar()plt.grid(False)plt.show()

结果:

tensorflow文档教程(tensorflow与pytorch的区别)

5. 重点来了,创建神经网络模型

过程: 1. 配置 ;2.编译

i. 建顺序层

模型的基本单位是层。使用keras会比传统手工更容易创建一个层:

model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax')])

第1个层:tf.keras.layers.Flatten,将图片从2维(2828像素)数组,转成一维数组(2828=784像素)。这个层只是把数据平面化。下面是两个tf.keras.layers.Dense层,它们称为紧密连接或全连接、或神经层。1层有128个神经节点,第二个有10节点的softmax激活函数,它返回 10个可能性分值,这些分值总和是1.每个节点都表示当前图片属于哪种分类的分值。

2. 编译模型

编译要定义三个参数:

  • 损失函数
  • 优化器
  • 评估指标:用来监视训练和测试的步骤。下面是使用accuracy。
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

3. 训练模型 ,3个步骤:

  1. 输入训练数据
  2. 模型学习图片和标注间的规律
  3. 测试集测试

开始训练:

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

训练过程中会显示损失值、准确度。

tensorflow文档教程(tensorflow与pytorch的区别)

5. 预测

这里使用测试集试试预测效果:

predictions = model.predict(test_images)

tensorflow文档教程(tensorflow与pytorch的区别)

输出是一个数组,表示属于10种分类的可能性值。使用argmax取最大置信度的值:看看和标注值可一致:

print('predict = %i; label=%i' % (np.argmax(predictions[0]),test_labels[0]))

tensorflow文档教程(tensorflow与pytorch的区别)

三、完整程序:

from __future__ import absolute_import, division, print_function, unicode_literals# TensorFlow and tf.kerasimport tensorflow as tffrom tensorflow import keras# Helper librariesimport numpy as npimport matplotlib.pyplot as pltprint(tf.__version__)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']train_images = train_images / 255.0test_images = test_images / 255.0model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(train_images, train_labels, epochs=10)test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)print('nTest accuracy:', test_acc)predictions = model.predict(test_images)print('predict = %i; label=%i' % (np.argmax(predictions[0]),test_labels[0]))
(0)
小多多的头像小多多创始人

相关推荐

发表回复

登录后才能评论