欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

深度学习:原理与实现(基于tensorflow实现图像分类)

程序员文章站 2022-03-06 16:05:51
...

1. 人工神经网络

1.1 神经网络结构

深度学习:原理与实现(基于tensorflow实现图像分类)
人工神经网络(简称神经网络)是模拟人类大脑神经元构造的一个数学计算模型。
一个神经网络的搭建,需要满足三个条件。

  1. 输入和输出
  2. 权重(w)和阈值(b)
  3. 多层感知器的结构

1.2 神经网络运作过程

其中,最困难的部分就是确定权重(w)和阈值(b)。必需有一种方法,可以找出答案。

这种方法就是试错法。其他参数都不变,w(或b)的微小变动,记作Δw(或Δb),然后观察输出有什么变化。不断重复这个过程,直至得到对应最精确输出的那组w和b,就是我们要的值。这个过程称为模型的训练。

因此,神经网络的运作过程如下。

  1. 确定输入和输出
  2. 找到一种或多种算法,可以从输入得到输出(前向传播
  3. 找到一组已知答案的数据集,用来训练模型,估算w和b (后向传播
  4. 一旦新的数据产生,输入模型,就可以得到结果,同时对w和b进行校正

整个过程需要海量计算。所以,神经网络直到最近这几年才有实用价值,而且一般的 CPU 还不行,要使用专门为机器学习定制的 GPU 来计算。

1.3 输出的连续性

上面的模型有一个问题没有解决,按照假设,输出只有两种结果:0和1。但是,模型要求w或b的微小变化,会引发输出的变化。如果只输出0和1,未免也太不敏感了,无法保证训练的正确性,因此必须将"输出"改造成一个连续性函数。

这就需要进行一点简单的数学改造。

首先,将感知器的计算结果wx + b记为z。
深度学习:原理与实现(基于tensorflow实现图像分类)

z = wx + b

然后,计算下面的式子,将结果记为σ(z)。
深度学习:原理与实现(基于tensorflow实现图像分类)

σ(z) = 1 / (1 + e^(-z))  # **函数

这是因为如果z趋向正无穷z → +∞(表示感知器强烈匹配),那么σ(z) → 1;如果z趋向负无穷z → -∞(表示感知器强烈不匹配),那么σ(z) → 0。也就是说,只要使用σ(z)当作输出结果,那么输出就会变成一个连续性函数。

2. 基于tensorflow实现FASION MINIST图像分类

深度学习:原理与实现(基于tensorflow实现图像分类)

2.1 加载并准备 MNIST 数据集[image, lable]

dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True)
train_dataset, test_dataset = dataset['train'], dataset['test']

分为10个类别

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

每张图片像素28*28,每个像素值【0-255】;预处理,像素值由【0-255】转换到【0-1】。

def normalize(images, labels):
  images = tf.cast(images, tf.float32)
  images /= 255
  return images, labels

# The map function applies the normalize function to each element in the train
# and test datasets
train_dataset =  train_dataset.map(normalize)
test_dataset  =  test_dataset.map(normalize)

# The first time you use the dataset, the images will be loaded from disk
# Caching will keep them in memory, making training faster
train_dataset =  train_dataset.cache()
test_dataset  =  test_dataset.cache()
BATCH_SIZE = 32
train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)

2.2 构建神经网络

我们将要构建的神经网络,输入层共有784个神经元,输出层共有10个神经元:

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28, 1)), # 输入层: This layer transforms the images from a 2d-array of 28  ×  28 pixels, to a 1d-array of 784 pixels (28*28). 
    tf.keras.layers.Dense(128, activation=tf.nn.relu), # 隐藏层:A densely connected layer of 128 neurons. Each neuron (or node) takes input from all 784 nodes in the previous layer, weighting that input according to hidden parameters which will be learned during training, and outputs a single value to the next layer.
    tf.keras.layers.Dense(10) # 输出层:A 10-node softmax layer, with each node representing a class of clothing. As in the previous layer, each node takes input from the 128 nodes in the layer before it. Each node weights the input according to learned parameters, and then outputs a value in the range [0, 1], representing the probability that the image belongs to that class. The sum of all 10 node values is 1.
])

2.3 为训练选择优化器与损失函数

model.compile(optimizer='adam', #  Optimizer —An algorithm for adjusting the inner parameters of the model in order to minimize loss
			# 优化函数:最优化的目标就是找到能够使损失函数值最小化的一系列W
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), # Loss function — An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss.
              # 损失函数:神经网络模型训练得以实现是经过前向传播计算Loss,根据Loss的值进行反向推导,并进行相关参数的调整。使用的最主要的损失函数是均方误差和交叉熵误差。
              metrics=['accuracy']) # Metrics —Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified.

2.4 使用训练集,训练模型

model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE)) # 训练模型
# 神经网络利用训练数据进行学习,并用测试数据评价学习到的模型
# 神经网络的训练是以损失函数为指标进行的,更新权重以及偏移量,最终使得损失函数的值不断减小。

2.5 使用测试集,评价训练模型

test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))
print('Accuracy on test dataset:', test_accuracy)

2.6 使用模型,预测图片类别

for test_images, test_labels in test_dataset.take(1):
  test_images = test_images.numpy()
  test_labels = test_labels.numpy()
  predictions = model.predict(test_images)

参考

http://www.ruanyifeng.com/blog/2017/07/neural-network.html
https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/tutorials/quickstart/advanced.ipynb

相关标签: AI