0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

【连载】深度学习笔记12:卷积神经网络的Tensorflow实现

人工智能实训营 2018-10-30 18:50 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

在上一讲中,我们学习了如何利用 numpy 手动搭建卷积神经网络。但在实际的图像识别中,使用 numpy 去手写 CNN 未免有些吃力不讨好。在 DNN 的学习中,我们也是在手动搭建之后利用 Tensorflow 去重新实现一遍,一来为了能够对神经网络的传播机制能够理解更加透彻,二来也是为了更加高效使用开源框架快速搭建起深度学习项目。本节就继续和大家一起学习如何利用 Tensorflow 搭建一个卷积神经网络。

我们继续以 NG 课题组提供的 sign 手势数据集为例,学习如何通过 Tensorflow 快速搭建起一个深度学习项目。数据集标签共有零到五总共 6 类标签,示例如下:


先对数据进行简单的预处理并查看训练集和测试集维度:

X_train = X_train_orig/255.
X_test = X_test_orig/255.
Y_train = convert_to_one_hot(Y_train_orig, 6).T Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape))

640?wx_fmt=png
可见我们总共有 1080 张 64643 训练集图像,120 张 64643 的测试集图像,共有 6 类标签。下面我们开始搭建过程。

创建 placeholder

首先需要为训练集预测变量和目标变量创建占位符变量 placeholder ,定义创建占位符变量函数:

def create_placeholders(n_H0, n_W0, n_C0, n_y):  
""" Creates the placeholders for the tensorflow session. Arguments: n_H0 -- scalar, height of an input image n_W0 -- scalar, width of an input image n_C0 -- scalar, number of channels of the input n_y -- scalar, number of classes Returns: X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float" Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float" """ X = tf.placeholder(tf.float32, shape=(None, n_H0, n_W0, n_C0), name='X') Y = tf.placeholder(tf.float32, shape=(None, n_y), name='Y')
return X, Y
参数初始化

然后需要对滤波器权值参数进行初始化:

def initialize_parameters():  
""" Initializes weight parameters to build a neural network with tensorflow. Returns: parameters -- a dictionary of tensors containing W1, W2 """ tf.set_random_seed(1) W1 = tf.get_variable("W1", [4,4,3,8], initializer = tf.contrib.layers.xavier_initializer(seed = 0)) W2 = tf.get_variable("W2", [2,2,8,16], initializer = tf.contrib.layers.xavier_initializer(seed = 0)) parameters = {"W1": W1,
"W2": W2}
return parameters
执行卷积网络的前向传播过程

640?wx_fmt=png
前向传播过程如下所示:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED


可见我们要搭建的是一个典型的 CNN 过程,经过两次的卷积-relu激活-最大池化,然后展开接上一个全连接层。利用
Tensorflow 搭建上述传播过程如下:

def forward_propagation(X, parameters):  
""" Implements the forward propagation for the model Arguments: X -- input dataset placeholder, of shape (input size, number of examples) parameters -- python dictionary containing your parameters "W1", "W2" the shapes are given in initialize_parameters Returns: Z3 -- the output of the last LINEAR unit """ # Retrieve the parameters from the dictionary "parameters" W1 = parameters['W1'] W2 = parameters['W2']
# CONV2D: stride of 1, padding 'SAME' Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME')
# RELU A1 = tf.nn.relu(Z1)
# MAXPOOL: window 8x8, sride 8, padding 'SAME' P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME')
# CONV2D: filters W2, stride 1, padding 'SAME' Z2 = tf.nn.conv2d(P1,W2, strides = [1,1,1,1], padding = 'SAME')
# RELU A2 = tf.nn.relu(Z2)
# MAXPOOL: window 4x4, stride 4, padding 'SAME' P2 = tf.nn.max_pool(A2, ksize = [1,4,4,1], strides = [1,4,4,1], padding = 'SAME')
# FLATTEN P2 = tf.contrib.layers.flatten(P2) Z3 = tf.contrib.layers.fully_connected(P2, 6, activation_fn = None)
return Z3
计算当前损失

Tensorflow 中计算损失函数非常简单,一行代码即可:

def compute_cost(Z3, Y):  
""" Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the cost function """ cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z3, labels=Y))
return cost

定义好上述过程之后,就可以封装整体的训练过程模型。可能你会问为什么没有反向传播,这里需要注意的是 Tensorflow 帮助我们自动封装好了反向传播过程,无需我们再次定义,在实际搭建过程中我们只需将前向传播的网络结构定义清楚即可。

封装模型
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009,
     num_epochs = 100, minibatch_size = 64, print_cost = True):  
""" Implements a three-layer ConvNet in Tensorflow: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED Arguments: X_train -- training set, of shape (None, 64, 64, 3) Y_train -- test set, of shape (None, n_y = 6) X_test -- training set, of shape (None, 64, 64, 3) Y_test -- test set, of shape (None, n_y = 6) learning_rate -- learning rate of the optimization num_epochs -- number of epochs of the optimization loop minibatch_size -- size of a minibatch print_cost -- True to print the cost every 100 epochs Returns: train_accuracy -- real number, accuracy on the train set (X_train) test_accuracy -- real number, testing accuracy on the test set (X_test) parameters -- parameters learnt by the model. They can then be used to predict. """ ops.reset_default_graph() tf.set_random_seed(1) seed = 3 (m, n_H0, n_W0, n_C0) = X_train.shape n_y = Y_train.shape[1] costs = [] # Create Placeholders of the correct shape X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)
# Initialize parameters parameters = initialize_parameters()
# Forward propagation Z3 = forward_propagation(X, parameters)
# Cost function cost = compute_cost(Z3, Y)
# Backpropagation optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) # Initialize all the variables globally init = tf.global_variables_initializer()
# Start the session to compute the tensorflow graph with tf.Session() as sess:
# Run the initialization sess.run(init)
# Do the training loop for epoch in range(num_epochs): minibatch_cost = 0. num_minibatches = int(m / minibatch_size) seed = seed + 1 minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)
for minibatch in minibatches:
# Select a minibatch (minibatch_X, minibatch_Y) = minibatch _ , temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y}) minibatch_cost += temp_cost / num_minibatches
# Print the cost every epoch if print_cost == True and epoch % 5 == 0:
print ("Cost after epoch %i: %f" % (epoch, minibatch_cost))
if print_cost == True and epoch % 1 == 0: costs.append(minibatch_cost)
# plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() # Calculate the correct predictions predict_op = tf.argmax(Z3, 1) correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
# Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print(accuracy) train_accuracy = accuracy.eval({X: X_train, Y: Y_train}) test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) print("Train Accuracy:", train_accuracy) print("Test Accuracy:", test_accuracy)

return train_accuracy, test_accuracy, parameters

对训练集执行模型训练:

_,_,parameters=model(X_train,Y_train,X_test,Y_test)

训练迭代过程如下:

640?wx_fmt=png


我们在训练集上取得了 0.67 的准确率,在测试集上的预测准确率为 0.58 ,虽然效果并不显著,模型也有待深度调优,但我们已经学会了如何用 Tensorflow 快速搭建起一个深度学习系统了。


声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 神经网络
    +关注

    关注

    42

    文章

    4842

    浏览量

    108166
  • AI
    AI
    +关注

    关注

    91

    文章

    41101

    浏览量

    302580
  • 人工智能
    +关注

    关注

    1820

    文章

    50324

    浏览量

    266925
  • 机器学习
    +关注

    关注

    67

    文章

    8564

    浏览量

    137217
  • 卷积神经网络

    关注

    4

    文章

    374

    浏览量

    12915
收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    人工智能-Python深度学习进阶与应用技术:工程师高培解读

    深度学习的工程化落地,早已不是纸上谈兵的事。从卷积神经网络到Transformer,从目标检测到大模型私有化部署,技术栈不断延伸,工程师面临的知识体系也越来越庞杂。现根据中际赛威工程师
    的头像 发表于 04-21 11:01 299次阅读
    人工智能-Python<b class='flag-5'>深度</b><b class='flag-5'>学习</b>进阶与应用技术:工程师高培解读

    FPGA实现CNN卷积层的高效窗口生成模块设计与验证

    卷积神经网络(CNN)可以分为卷积层、池化层、激活层、全链接层结构,本篇要实现的,就是CNN的卷积层中的window窗。
    的头像 发表于 04-15 10:35 150次阅读
    FPGA<b class='flag-5'>实现</b>CNN<b class='flag-5'>卷积</b>层的高效窗口生成模块设计与验证

    卷积神经网络如何让自动驾驶识别障碍物?

    自动驾驶的发展过程中,感知系统一直承担车辆“眼睛”的角色,其核心任务是让计算机理解复杂多变的物理世界。卷积神经网络(CNN)作为一种专门用于处理图像和视频等网格状数据结构的深度学习模型
    的头像 发表于 04-11 09:59 1447次阅读
    <b class='flag-5'>卷积</b><b class='flag-5'>神经网络</b>如何让自动驾驶识别障碍物?

    神经网络的初步认识

    日常生活中的智能应用都离不开深度学习,而深度学习则依赖于神经网络实现。什么是
    的头像 发表于 12-17 15:05 460次阅读
    <b class='flag-5'>神经网络</b>的初步认识

    自动驾驶中常提的卷积神经网络是个啥?

    在自动驾驶领域,经常会听到卷积神经网络技术。卷积神经网络,简称为CNN,是一种专门用来处理网格状数据(比如图像)的深度
    的头像 发表于 11-19 18:15 2246次阅读
    自动驾驶中常提的<b class='flag-5'>卷积</b><b class='flag-5'>神经网络</b>是个啥?

    CNN卷积神经网络设计原理及在MCU200T上仿真测试

    数的提出很大程度的解决了BP算法在优化深层神经网络时的梯度耗散问题。当x&gt;0 时,梯度恒为1,无梯度耗散问题,收敛快;当x&lt;0 时,该层的输出为0。 CNN
    发表于 10-29 07:49

    NMSIS神经网络库使用介绍

    :   神经网络卷积函数   神经网络激活函数   全连接层函数   神经网络池化函数   Softmax 函数   神经网络支持功能
    发表于 10-29 06:08

    构建CNN网络模型并优化的一般化建议

    整个模型非常巨大。所以要想实现轻量级的CNN神经网络模型,首先应该避免尝试单层神经网络。 2)减少卷积核的大小:CNN神经网络是通过权值共
    发表于 10-28 08:02

    卷积运算分析

    的数据,故设计了ConvUnit模块实现单个感受域规模的卷积运算. 卷积运算:不同于数学当中提及到的卷积概念,CNN神经网络中的
    发表于 10-28 07:31

    在Ubuntu20.04系统中训练神经网络模型的一些经验

    本帖欲分享在Ubuntu20.04系统中训练神经网络模型的一些经验。我们采用jupyter notebook作为开发IDE,以TensorFlow2为训练框架,目标是训练一个手写数字识别的神经网络
    发表于 10-22 07:03

    CICC2033神经网络部署相关操作

    读取。接下来需要使用扩展指令,完成神经网络的部署,此处仅对第一层卷积+池化的部署进行说明,其余层与之类似。 1.使用 Custom_Dtrans 指令,将权重数据、输入数据导入硬件加速器内。对于权重
    发表于 10-20 08:00

    液态神经网络(LNN):时间连续性与动态适应性的神经网络

    1.算法简介液态神经网络(LiquidNeuralNetworks,LNN)是一种新型的神经网络架构,其设计理念借鉴自生物神经系统,特别是秀丽隐杆线虫的神经结构,尽管这种微生物的
    的头像 发表于 09-28 10:03 1561次阅读
    液态<b class='flag-5'>神经网络</b>(LNN):时间连续性与动态适应性的<b class='flag-5'>神经网络</b>

    如何在机器视觉中部署深度学习神经网络

    图 1:基于深度学习的目标检测可定位已训练的目标类别,并通过矩形框(边界框)对其进行标识。 在讨论人工智能(AI)或深度学习时,经常会出现“神经网络
    的头像 发表于 09-10 17:38 1049次阅读
    如何在机器视觉中部署<b class='flag-5'>深度</b><b class='flag-5'>学习</b><b class='flag-5'>神经网络</b>

    卷积神经网络如何监测皮带堵料情况 #人工智能

    卷积神经网络
    jf_60804796
    发布于 :2025年07月01日 17:08:42

    神经网络专家系统在电机故障诊断中的应用

    摘要:针对传统专家系统不能进行自学习、自适应的问题,本文提出了基于种经网络专家系统的并步电机故障诊断方法。本文将小波神经网络和专家系统相结合,充分发挥了二者故障诊断的优点,很大程度上降低了对电机
    发表于 06-16 22:09