一步一步学用Tensorflow构建卷积神经网络

一步一步学用Tensorflow构建卷积神经网络,第1张

摘要: 本文主要和大家分享如何使用Tensorflow从头开始构建和训练卷积神经网络。这样就可以将这个知识作为一个构建块来创造有趣的深度学习应用程序了。

0. 简介
在过去,我写的主要都是“传统类”的机器学习文章,如朴素贝叶斯分类、逻辑回归和Perceptron算法。在过去的一年中,我一直在研究深度学习技术,因此,我想和大家分享一下如何使用Tensorflow从头开始构建和训练卷积神经网络。这样,我们以后就可以将这个知识作为一个构建块来创造有趣的深度学习应用程序了。

为此,你需要安装Tensorflow(请参阅安装说明),你还应该对Python编程和卷积神经网络背后的理论有一个基本的了解。安装完Tensorflow之后,你可以在不依赖GPU的情况下运行一个较小的神经网络,但对于更深层次的神经网络,就需要用到GPU的计算能力了。

在互联网上有很多解释卷积神经网络工作原理方面的网站和课程,其中有一些还是很不错的,图文并茂、易于理解[]。我在这里就不再解释相同的东西,所以在开始阅读下文之前,请提前了解卷积神经网络的工作原理。例如:

什么是卷积层,卷积层的过滤器是什么?

什么是激活层(ReLu层(应用最广泛的)、S型激活或tanh)?

什么是池层(最大池/平均池),什么是dropout?

随机梯度下降的工作原理是什么?

本文内容如下:
Tensorflow基础
1.1 常数和变量
1.2 Tensorflow中的图和会话
1.3 占位符和feed_dicts

Tensorflow中的神经网络
2.1 介绍
2.2 数据加载
2.3 创建一个简单的一层神经网络
2.4 Tensorflow的多个方面
2.5 创建LeNet5卷积神经网络
2.6 影响层输出大小的参数
2.7 调整LeNet5架构
2.8 学习速率和优化器的影响

Tensorflow中的深度神经网络
3.1 AlexNet
3.2 VGG Net-16
3.3 AlexNet性能

结语

1. Tensorflow 基础

在这里,我将向以前从未使用过Tensorflow的人做一个简单的介绍。如果你想要立即开始构建神经网络,或者已经熟悉Tensorflow,可以直接跳到第2节。如果你想了解更多有关Tensorflow的信息,你还可以查看这个代码库,或者阅读斯坦福大学CS20SI课程的讲义1和讲义2。

1.1 常量与变量
Tensorflow中最基本的单元是常量、变量和占位符。
tf.constant()和tf.Variable()之间的区别很清楚;一个常量有着恒定不变的值,一旦设置了它,它的值不能被改变。而变量的值可以在设置完成后改变,但变量的数据类型和形状无法改变。
#We can create constants and variables of different types.
#However, the different types do not mix well together.
a = tf.constant(2, tf.int16)
b = tf.constant(4, tf.float32)
c = tf.constant(8, tf.float32)

d = tf.Variable(2, tf.int16)
e = tf.Variable(4, tf.float32)
f = tf.Variable(8, tf.float32)

#we can perform computaTIons on variable of the same type: e + f
#but the following can not be done: d + e

#everything in Tensorflow is a tensor, these can have different dimensions:
#0D, 1D, 2D, 3D, 4D, or nD-tensors
g = tf.constant(np.zeros(shape=(2,2), dtype=np.float32)) #does work

h = tf.zeros([11], tf.int16)
i = tf.ones([2,2], tf.float32)
j = tf.zeros([1000,4,3], tf.float64)

k = tf.Variable(tf.zeros([2,2], tf.float32))
l = tf.Variable(tf.zeros([5,6,5], tf.float32))

除了tf.zeros()和tf.ones()能够创建一个初始值为0或1的张量(见这里)之外,还有一个tf.random_normal()函数,它能够创建一个包含多个随机值的张量,这些随机值是从正态分布中随机抽取的(默认的分布均值为0.0,标准差为1.0)。

另外还有一个tf.truncated_normal()函数,它创建了一个包含从截断的正态分布中随机抽取的值的张量,其中下上限是标准偏差的两倍。

有了这些知识,我们就可以创建用于神经网络的权重矩阵和偏差向量了。
weights = tf.Variable(tf.truncated_normal([256 * 256, 10]))
biases = tf.Variable(tf.zeros([10]))
print(weights.get_shape().as_list())
print(biases.get_shape().as_list())
>>>[65536, 10]
>>>[10]

1.2 Tensorflow 中的图与会话
在Tensorflow中,所有不同的变量以及对这些变量的 *** 作都保存在图(Graph)中。在构建了一个包含针对模型的所有计算步骤的图之后,就可以在会话(Session)中运行这个图了。会话可以跨CPU和GPU分配所有的计算。
graph = tf.Graph()
with graph.as_default():
a = tf.Variable(8, tf.float32)
b = tf.Variable(tf.zeros([2,2], tf.float32))

with tf.Session(graph=graph) as session:
tf.global_variables_iniTIalizer().run()
print(f)
print(session.run(f))
print(session.run(k))

>>>
>>> 8
>>> [[ 0. 0.]
>>> [ 0. 0.]]

1.3 占位符 与 feed_dicts
我们已经看到了用于创建常量和变量的各种形式。Tensorflow中也有占位符,它不需要初始值,仅用于分配必要的内存空间。 在一个会话中,这些占位符可以通过feed_dict填入(外部)数据。

以下是占位符的使用示例。
list_of_points1_ = [[1,2], [3,4], [5,6], [7,8]]
list_of_points2_ = [[15,16], [13,14], [11,12], [9,10]]
list_of_points1 = np.array([np.array(elem).reshape(1,2) for elem in list_of_points1_])
list_of_points2 = np.array([np.array(elem).reshape(1,2) for elem in list_of_points2_])

graph = tf.Graph()
with graph.as_default():
#we should use a tf.placeholder() to create a variable whose value you will fill in later (during session.run()).
#this can be done by 'feeding' the data into the placeholder.
#below we see an example of a method which uses two placeholder arrays of size [2,1] to calculate the eucledian distance

point1 = tf.placeholder(tf.float32, shape=(1, 2))
point2 = tf.placeholder(tf.float32, shape=(1, 2))

def calculate_eucledian_distance(point1, point2):
difference = tf.subtract(point1, point2)
power2 = tf.pow(difference, tf.constant(2.0, shape=(1,2)))
add = tf.reduce_sum(power2)
eucledian_distance = tf.sqrt(add)
return eucledian_distance

dist = calculate_eucledian_distance(point1, point2)

with tf.Session(graph=graph) as session:
tf.global_variables_iniTIalizer().run()
for ii in range(len(list_of_points1)):
point1_ = list_of_points1[ii]
point2_ = list_of_points2[ii]
feed_dict = {point1 : point1_, point2 : point2_}
distance = session.run([dist], feed_dict=feed_dict)
print("the distance between {} and {} -> {}".format(point1_, point2_, distance))

>>> the distance between [[1 2]] and [[15 16]] -> [19.79899]
>>> the distance between [[3 4]] and [[13 14]] -> [14.142136]
>>> the distance between [[5 6]] and [[11 12]] -> [8.485281]
>>> the distance between [[7 8]] and [[ 9 10]] -> [2.8284271]

2. Tensorflow 中的神经网络

2.1 简介

一步一步学用Tensorflow构建卷积神经网络,一步一步学用Tensorflow构建卷积神经网络,第2张

 

包含神经网络的图(如上图所示)应包含以下步骤:

1. 输入数据集:训练数据集和标签、测试数据集和标签(以及验证数据集和标签)。 测试和验证数据集可以放在tf.constant()中。而训练数据集被放在tf.placeholder()中,这样它可以在训练期间分批输入(随机梯度下降)。

2. 神经网络**模型**及其所有的层。这可以是一个简单的完全连接的神经网络,仅由一层组成,或者由5、9、16层组成的更复杂的神经网络。

3. 权重矩阵和**偏差矢量**以适当的形状进行定义和初始化。(每层一个权重矩阵和偏差矢量)

4. 损失值:模型可以输出分对数矢量(估计的训练标签),并通过将分对数与实际标签进行比较,计算出损失值(具有交叉熵函数的softmax)。损失值表示估计训练标签与实际训练标签的接近程度,并用于更新权重值。

5. 优化器:它用于将计算得到的损失值来更新反向传播算法中的权重和偏差。

2.2 数据加载
下面我们来加载用于训练和测试神经网络的数据集。为此,我们要下载MNIST和CIFAR-10数据集。 MNIST数据集包含了6万个手写数字图像,其中每个图像大小为28 x 28 x 1(灰度)。 CIFAR-10数据集也包含了6万个图像(3个通道),大小为32 x 32 x 3,包含10个不同的物体(飞机、汽车、鸟、猫、鹿、狗、青蛙、马、船、卡车)。 由于两个数据集中都有10个不同的对象,所以这两个数据集都包含10个标签。

一步一步学用Tensorflow构建卷积神经网络,一步一步学用Tensorflow构建卷积神经网络,第3张

 

首先,我们来定义一些方便载入数据和格式化数据的方法。
def randomize(dataset, labels):
permutaTIon = np.random.permutation(labels.shape[0])
shuffled_dataset = dataset[permutation, :, :]
shuffled_labels = labels[permutation]
return shuffled_dataset, shuffled_labels

def one_hot_encode(np_array):
return (np.arange(10) == np_array[:,None]).astype(np.float32)

def reformat_data(dataset, labels, image_width, image_height, image_depth):
np_dataset_ = np.array([np.array(image_data).reshape(image_width, image_height, image_depth) for image_data in dataset])
np_labels_ = one_hot_encode(np.array(labels, dtype=np.float32))
np_dataset, np_labels = randomize(np_dataset_, np_labels_)
return np_dataset, np_labels

def flatten_tf_array(array):
shape = array.get_shape().as_list()
return tf.reshape(array, [shape[0], shape[1] shape[2] shape[3]])

def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0])

这些方法可用于对标签进行独热码编码、将数据加载到随机数组中、扁平化矩阵(因为完全连接的网络需要一个扁平矩阵作为输入):

在我们定义了这些必要的函数之后,我们就可以这样加载MNIST和CIFAR-10数据集了:
mnist_folder = './data/mnist/'
mnist_image_width = 28
mnist_image_height = 28
mnist_image_depth = 1
mnist_num_labels = 10

mndata = MNIST(mnist_folder)
mnist_train_dataset_, mnist_train_labels_ = mndata.load_training()
mnist_test_dataset_, mnist_test_labels_ = mndata.load_testing()

mnist_train_dataset, mnist_train_labels = reformat_data(mnist_train_dataset_, mnist_train_labels_, mnist_image_size, mnist_image_size, mnist_image_depth)
mnist_test_dataset, mnist_test_labels = reformat_data(mnist_test_dataset_, mnist_test_labels_, mnist_image_size, mnist_image_size, mnist_image_depth)

print("There are {} images, each of size {}".format(len(mnist_train_dataset), len(mnist_train_dataset[0])))
print("Meaning each image has the size of 28281 = {}".format(mnist_image_sizemnist_image_size1))
print("The training set contains the following {} labels: {}".format(len(np.unique(mnist_train_labels_)), np.unique(mnist_train_labels_)))

print('Training set shape', mnist_train_dataset.shape, mnist_train_labels.shape)
print('Test set shape', mnist_test_dataset.shape, mnist_test_labels.shape)

train_dataset_mnist, train_labels_mnist = mnist_train_dataset, mnist_train_labels
test_dataset_mnist, test_labels_mnist = mnist_test_dataset, mnist_test_labels

######################################################################################

cifar10_folder = './data/cifar10/'
train_datasets = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5', ]
test_dataset = ['test_batch']
c10_image_height = 32
c10_image_width = 32
c10_image_depth = 3
c10_num_labels = 10

with open(cifar10_folder + test_dataset[0], 'rb') as f0:
c10_test_dict = pickle.load(f0, encoding='bytes')

c10_test_dataset, c10_test_labels = c10_test_dict[b'data'], c10_test_dict[b'labels']
test_dataset_cifar10, test_labels_cifar10 = reformat_data(c10_test_dataset, c10_test_labels, c10_image_size, c10_image_size, c10_image_depth)

c10_train_dataset, c10_train_labels = [], []
for train_dataset in train_datasets:
with open(cifar10_folder + train_dataset, 'rb') as f0:
c10_train_dict = pickle.load(f0, encoding='bytes')
c10_train_dataset_, c10_train_labels_ = c10_train_dict[b'data'], c10_train_dict[b'labels']

c10_train_dataset.append(c10_train_dataset_)
c10_train_labels += c10_train_labels_

c10_train_dataset = np.concatenate(c10_train_dataset, axis=0)
train_dataset_cifar10, train_labels_cifar10 = reformat_data(c10_train_dataset, c10_train_labels, c10_image_size, c10_image_size, c10_image_depth)
del c10_train_dataset
del c10_train_labels

print("The training set contains the following labels: {}".format(np.unique(c10_train_dict[b'labels'])))
print('Training set shape', train_dataset_cifar10.shape, train_labels_cifar10.shape)
print('Test set shape', test_dataset_cifar10.shape, test_labels_cifar10.shape)

你可以从Yann LeCun的网站下载MNIST数据集。下载并解压缩之后,可以使用python-mnist 工具来加载数据。 CIFAR-10数据集可以从这里下载。

2.3 创建一个简单的一层神经网络
神经网络最简单的形式是一层线性全连接神经网络(FCNN, Fully Connected Neural Network)。 在数学上它由一个矩阵乘法组成。

最好是在Tensorflow中从这样一个简单的NN开始,然后再去研究更复杂的神经网络。 当我们研究那些更复杂的神经网络的时候,只是图的模型(步骤2)和权重(步骤3)发生了改变,其他步骤仍然保持不变。

我们可以按照如下代码制作一层FCNN:
image_width = mnist_image_width
image_height = mnist_image_height
image_depth = mnist_image_depth
num_labels = mnist_num_labels

#the dataset
train_dataset = mnist_train_dataset
train_labels = mnist_train_labels
test_dataset = mnist_test_dataset
test_labels = mnist_test_labels

#number of iterations and learning rate
num_steps = 10001
display_step = 1000
learning_rate = 0.5

graph = tf.Graph()
with graph.as_default():
#1) First we put the input data in a Tensorflow friendly form.
tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_width, image_height, image_depth))
tf_train_labels = tf.placeholder(tf.float32, shape = (batch_size, num_labels))
tf_test_dataset = tf.constant(test_dataset, tf.float32)

#2) Then, the weight matrices and bias vectors are initialized
#as a default, tf.truncated_normal() is used for the weight matrix and tf.zeros() is used for the bias vector.
weights = tf.Variable(tf.truncated_normal([image_width image_height image_depth, num_labels]), tf.float32)
bias = tf.Variable(tf.zeros([num_labels]), tf.float32)

#3) define the model:
#A one layered fccd simply consists of a matrix multiplication
def model(data, weights, bias):
return tf.matmul(flatten_tf_array(data), weights) + bias

logits = model(tf_train_dataset, weights, bias)

#4) calculate the loss, which will be used in the optimization of the weights
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels))

#5) Choose an optimizer. Many are available.
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

#6) The predicted values for the images in the train dataset and test dataset are assigned to the variables train_prediction and test_prediction.
#It is only necessary if you want to know the accuracy by comparing it with the actual values.
train_prediction = tf.nn.softmax(logits)
test_prediction = tf.nn.softmax(model(tf_test_dataset, weights, bias))

with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
print('Initialized')
for step in range(num_steps):
_, l, predictions = session.run([optimizer, loss, train_prediction])
if (step % display_step == 0):
train_accuracy = accuracy(predictions, train_labels[:, :])
test_accuracy = accuracy(test_prediction.eval(), test_labels)
message = "step {:04d} : loss is {:06.2f}, accuracy on training set {:02.2f} %, accuracy on test set {:02.2f} %".format(step, l, train_accuracy, test_accuracy)
print(message)

>>> Initialized
>>> step 0000 : loss is 2349.55, accuracy on training set 10.43 %, accuracy on test set 34.12 %
>>> step 0100 : loss is 3612.48, accuracy on training set 89.26 %, accuracy on test set 90.15 %
>>> step 0200 : loss is 2634.40, accuracy on training set 91.10 %, accuracy on test set 91.26 %
>>> step 0300 : loss is 2109.42, accuracy on training set 91.62 %, accuracy on test set 91.56 %
>>> step 0400 : loss is 2093.56, accuracy on training set 91.85 %, accuracy on test set 91.67 %
>>> step 0500 : loss is 2325.58, accuracy on training set 91.83 %, accuracy on test set 91.67 %
>>> step 0600 : loss is 22140.44, accuracy on training set 68.39 %, accuracy on test set 75.06 %
>>> step 0700 : loss is 5920.29, accuracy on training set 83.73 %, accuracy on test set 87.76 %
>>> step 0800 : loss is 9137.66, accuracy on training set 79.72 %, accuracy on test set 83.33 %
>>> step 0900 : loss is 15949.15, accuracy on training set 69.33 %, accuracy on test set 77.05 %
>>> step 1000 : loss is 1758.80, accuracy on training set 92.45 %, accuracy on test set 91.79 %

在图中,我们加载数据,定义权重矩阵和模型,从分对数矢量中计算损失值,并将其传递给优化器,该优化器将更新迭代“num_steps”次数的权重。

在上述完全连接的NN中,我们使用了梯度下降优化器来优化权重。然而,有很多不同的优化器可用于Tensorflow。 最常用的优化器有GradientDescentOptimizer、AdamOptimizer和AdaGradOptimizer,所以如果你正在构建一个CNN的话,我建议你试试这些。

Sebastian Ruder有一篇不错的博文介绍了不同优化器之间的区别,通过这篇文章,你可以更详细地了解它们。

2.4 Tensorflow的几个方面
Tensorflow包含许多层,这意味着可以通过不同的抽象级别来完成相同的 *** 作。这里有一个简单的例子, *** 作
logits = tf.matmul(tf_train_dataset, weights) + biases,

也可以这样来实现
logits = tf.nn.xw_plus_b(train_dataset, weights, biases)。

这是layers API中最明显的一层,它是一个具有高度抽象性的层,可以很容易地创建由许多不同层组成的神经网络。例如,或函数用于创建卷积和完全连接的层。通过这些函数,可以将层数、过滤器的大小或深度、激活函数的类型等指定为参数。然后,权重矩阵和偏置矩阵会自动创建,一起创建的还有激活函数和丢弃正则化层(dropout regularization laye)。

例如,通过使用 层API,下面这些代码:
import Tensorflow as tf

w1 = tf.Variable(tf.truncated_normal([filter_size, filter_size, image_depth, filter_depth], stddev=0.1))
b1 = tf.Variable(tf.zeros([filter_depth]))

layer1_conv = tf.nn.conv2d(data, w1, [1, 1, 1, 1], padding='SAME')
layer1_relu = tf.nn.relu(layer1_conv + b1)
layer1_pool = tf.nn.max_pool(layer1_pool, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')

可以替换为
from tflearn.layers.conv import conv_2d, max_pool_2d
layer1_conv = conv_2d(data, filter_depth, filter_size, activation='relu')
layer1_pool = max_pool_2d(layer1_conv_relu, 2, strides=2)

可以看到,我们不需要定义权重、偏差或激活函数。尤其是在你建立一个具有很多层的神经网络的时候,这样可以保持代码的清晰和整洁。

然而,如果你刚刚接触Tensorflow的话,学习如何构建不同种类的神经网络并不合适,因为tflearn做了所有的工作。

因此,我们不会在本文中使用层API,但是一旦你完全理解了如何在Tensorflow中构建神经网络,我还是建议你使用它。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/dianzi/2601154.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-08-09
下一篇 2022-08-09

发表评论

登录后才能评论

评论列表(0条)

保存