这篇文章讲解的是使用Tensorflow实现残差网络resnet-50. 侧重点不在于理论部分,而是在于代码实现部分。在github上面已经有其他的开源实现,如果希望直接使用代码运行自己的数据,不建议使用本人的代码。但是如果希望学习resnet的代码实现思路,那么阅读本文将是一个不错的选择,因为本文的代码的思路是很清晰的。如果你刚刚阅读完resnet的那篇论文,非常建议你进一步学习如何使用代码实现resnet。本文包含源码的数据集。

resnet只是在CNN上面增加了shortcut,所以,resnet和CNN是很相似的。

##1. model
下面将要实现的是resnet-50。下面是网络模型的整体模型图。其中的CONV表示卷积层,Batch Norm表示Batch 归一化层,ID BLOCK表示Identity块,由多个层构成,具体见第二个图。Conv BLOCK表示卷积块,由多个层构成。为了使得model个结构更加清晰,才提取出了conv block 和id block两个‘块’,分别把它们封装成函数。

如果不了解batch norm,可以暂时滤过这部分的内容,可以把它看作是一个特殊的层,它不会改变数据的维度。这将不影响对resnet实现的理解。

具体见第三个图。

上图表示Resnet-50的整体结构图


上图表示ID block


上图表示conv block

##2. 数据

输入的是类似上图所示的手势图片数据,总共有6个类。所给的数据已经加工过,是‘.h5’格式的数据。有1080张图片,120张测试数据。每一张图片是一个64x64的RGB图片。具体的数据格式为:

number of training examples = 1080
number of test examples = 120
X_train shape: (1080, 64, 64, 3)
Y_train shape: (1080, 6)
X_test shape: (120, 64, 64, 3)
Y_test shape: (120, 6)
x train max,  0.956; x train min,  0.015
x test max,  0.94; x test min,  0.011

3. 目标

训练一个模型,使之能够判别图片中的手指所代表的数字。实质上这个是属于多分类问题。所以,模型的输入是一个64x64x3的图片;模型的输出层为6个节点,每一个节点表示一种分类。

4. 模型实现

identity block的实现,对于上图2。需要注意的是,X_shortcut一开始就保存了所传入的数据,然后在函数的末尾部分再加上X_shortcut。除了这一点,其他点跟CNN是一样的。

    def identity_block(self, X_input, kernel_size, in_filter, out_filters, stage, block, training):"""Implementation of the identity block as defined in Figure 3Arguments:X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)kernel_size -- integer, specifying the shape of the middle CONV's window for the main pathfilters -- python list of integers, defining the number of filters in the CONV layers of the main pathstage -- integer, used to name the layers, depending on their position in the networkblock -- string/character, used to name the layers, depending on their position in the networktraining -- train or testReturns:X -- output of the identity block, tensor of shape (n_H, n_W, n_C)"""# defining name basisblock_name = 'res' + str(stage) + blockf1, f2, f3 = out_filterswith tf.variable_scope(block_name):X_shortcut = X_input#firstW_conv1 = self.weight_variable([1, 1, in_filter, f1])X = tf.nn.conv2d(X_input, W_conv1, strides=[1, 1, 1, 1], padding='SAME')X = tf.layers.batch_normalization(X, axis=3, training=training)X = tf.nn.relu(X)#secondW_conv2 = self.weight_variable([kernel_size, kernel_size, f1, f2])X = tf.nn.conv2d(X, W_conv2, strides=[1, 1, 1, 1], padding='SAME')X = tf.layers.batch_normalization(X, axis=3, training=training)X = tf.nn.relu(X)#thirdW_conv3 = self.weight_variable([1, 1, f2, f3])X = tf.nn.conv2d(X, W_conv3, strides=[1, 1, 1, 1], padding='VALID')X = tf.layers.batch_normalization(X, axis=3, training=training)#final stepadd = tf.add(X, X_shortcut)add_result = tf.nn.relu(add)return add_result

下面是conv block,对应于上面图片3.

    def convolutional_block(self, X_input, kernel_size, in_filter,out_filters, stage, block, training, stride=2):"""Implementation of the convolutional block as defined in Figure 4Arguments:X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)kernel_size -- integer, specifying the shape of the middle CONV's window for the main pathfilters -- python list of integers, defining the number of filters in the CONV layers of the main pathstage -- integer, used to name the layers, depending on their position in the networkblock -- string/character, used to name the layers, depending on their position in the networktraining -- train or teststride -- Integer, specifying the stride to be usedReturns:X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C)"""# defining name basisblock_name = 'res' + str(stage) + blockwith tf.variable_scope(block_name):f1, f2, f3 = out_filtersx_shortcut = X_input#firstW_conv1 = self.weight_variable([1, 1, in_filter, f1])X = tf.nn.conv2d(X_input, W_conv1,strides=[1, stride, stride, 1],padding='VALID')X = tf.layers.batch_normalization(X, axis=3, training=training)X = tf.nn.relu(X)#secondW_conv2 = self.weight_variable([kernel_size, kernel_size, f1, f2])X = tf.nn.conv2d(X, W_conv2, strides=[1,1,1,1], padding='SAME')X = tf.layers.batch_normalization(X, axis=3, training=training)X = tf.nn.relu(X)#thirdW_conv3 = self.weight_variable([1,1, f2,f3])X = tf.nn.conv2d(X, W_conv3, strides=[1, 1, 1,1], padding='VALID')X = tf.layers.batch_normalization(X, axis=3, training=training)#shortcut pathW_shortcut = self.weight_variable([1, 1, in_filter, f3])x_shortcut = tf.nn.conv2d(x_shortcut, W_shortcut, strides=[1, stride, stride, 1], padding='VALID')#finaladd = tf.add(x_shortcut, X)add_result = tf.nn.relu(add)return add_result

下面是模型的整合,对应于上图1。

    def deepnn(self, x_input, classes=6):"""Implementation of the popular ResNet50 the following architecture:CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYERArguments:Returns:"""x = tf.pad(x_input, tf.constant([[0, 0], [3, 3, ], [3, 3], [0, 0]]), "CONSTANT")with tf.variable_scope('reference') :training = tf.placeholder(tf.bool, name='training')#stage 1w_conv1 = self.weight_variable([7, 7, 3, 64])x = tf.nn.conv2d(x, w_conv1, strides=[1, 2, 2, 1], padding='VALID')x = tf.layers.batch_normalization(x, axis=3, training=training)x = tf.nn.relu(x)x = tf.nn.max_pool(x, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1], padding='VALID')assert (x.get_shape() == (x.get_shape()[0], 15, 15, 64))#stage 2x = self.convolutional_block(x, 3, 64, [64, 64, 256], 2, 'a', training, stride=1)x = self.identity_block(x, 3, 256, [64, 64, 256], stage=2, block='b', training=training)x = self.identity_block(x, 3, 256, [64, 64, 256], stage=2, block='c', training=training)#stage 3x = self.convolutional_block(x, 3, 256, [128,128,512], 3, 'a', training)x = self.identity_block(x, 3, 512, [128,128,512], 3, 'b', training=training)x = self.identity_block(x, 3, 512, [128,128,512], 3, 'c', training=training)x = self.identity_block(x, 3, 512, [128,128,512], 3, 'd', training=training)#stage 4x = self.convolutional_block(x, 3, 512, [256, 256, 1024], 4, 'a', training)x = self.identity_block(x, 3, 1024, [256, 256, 1024], 4, 'b', training=training)x = self.identity_block(x, 3, 1024, [256, 256, 1024], 4, 'c', training=training)x = self.identity_block(x, 3, 1024, [256, 256, 1024], 4, 'd', training=training)x = self.identity_block (x, 3, 1024, [256, 256, 1024], 4, 'e', training=training)x = self.identity_block(x, 3, 1024, [256, 256, 1024], 4, 'f', training=training)#stage 5x = self.convolutional_block(x, 3, 1024, [512, 512, 2048], 5, 'a', training)x = self.identity_block(x, 3, 2048, [512, 512, 2048], 5, 'b', training=training)x = self.identity_block(x, 3, 2048, [512, 512, 2048], 5, 'c', training=training)x = tf.nn.avg_pool(x, [1, 2, 2, 1], strides=[1,1,1,1], padding='VALID')flatten = tf.layers.flatten(x)x = tf.layers.dense(flatten, units=50, activation=tf.nn.relu)# Dropout - controls the complexity of the model, prevents co-adaptation of# features.with tf.name_scope('dropout'):keep_prob = tf.placeholder(tf.float32)x = tf.nn.dropout(x, keep_prob)logits = tf.layers.dense(x, units=6, activation=tf.nn.softmax)return logits, keep_prob, training

5. 代价函数

使用交叉熵来计算损失函数和代价函数。这里没有使用L2正则化。

    def cost(self, logits, labels):with tf.name_scope('loss'):# cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y_conv)cross_entropy = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)cross_entropy_cost = tf.reduce_mean(cross_entropy)return cross_entropy_cost

在训练模型的时候,应该控制迭代的次数,以避免过度的过拟合。刚开始的时候,所打印出来的cost值会上下浮动,这个是正常的(一开始本人以为是模型有问题,后来才知道这是正常的)耐心等待便好。训练的模型将保存在硬盘中,在预测的时候可直接读取这些数据。

    def train(self, X_train, Y_train):features = tf.placeholder(tf.float32, [None, 64, 64, 3])labels = tf.placeholder(tf.int64, [None, 6])logits, keep_prob, train_mode = self.deepnn(features)cross_entropy = self.cost(logits, labels)with tf.name_scope('adam_optimizer'):update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)with tf.control_dependencies(update_ops):train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)graph_location = tempfile.mkdtemp()print('Saving graph to: %s' % graph_location)train_writer = tf.summary.FileWriter(graph_location)train_writer.add_graph(tf.get_default_graph())mini_batches = random_mini_batches(X_train, Y_train, mini_batch_size=32, seed=None)saver = tf.train.Saver()with tf.Session() as sess:sess.run(tf.global_variables_initializer())for i in range(1000):X_mini_batch, Y_mini_batch = mini_batches[np.random.randint(0, len(mini_batches))]train_step.run(feed_dict={features: X_mini_batch, labels: Y_mini_batch, keep_prob: 0.5, train_mode: True})if i % 20 == 0:train_cost = sess.run(cross_entropy, feed_dict={features: X_mini_batch,labels: Y_mini_batch, keep_prob: 1.0, train_mode: False})print('step %d, training cost %g' % (i, train_cost))saver.save(sess, self.model_save_path)

模型预测。先初始化graph,然后读取硬盘中模型参数数据。

    def evaluate(self, test_features, test_labels, name='test '):tf.reset_default_graph()x = tf.placeholder(tf.float32, [None, 64, 64, 3])y_ = tf.placeholder(tf.int64, [None, 6])logits, keep_prob, train_mode = self.deepnn(x)accuracy = self.accuracy(logits, y_)saver = tf.train.Saver()with tf.Session() as sess:saver.restore(sess, self.model_save_path)accu = sess.run(accuracy, feed_dict={x: test_features, y_: test_labels,keep_prob: 1.0, train_mode: False})print('%s accuracy %g' % (name, accu))

这个本人测试的结果

本算法只是单纯地实现和演示ResNet-50神经网络模型,所以在运行地时候出现结果时好时坏地现象,也就是结果不稳定。如果加上滑动平均模型,就会稳定很多。

本文的思路来自吴恩达老师关于深度学习第四课的课程。

数据集下载:链接:https://pan.baidu.com/s/1iA004kLU1gocvA-gaiwSWw
提取码:sqj3

完整源码下载:https://github.com/liangyihuai/my_tensorflow/blob/master/com/huai/converlution/resnets/hand_classifier_with_resnet.py

使用Tensorflow实现残差网络ResNet-50相关推荐

  1. 深度残差网络RESNET

    一.残差神经网络--ResNet的综述 深度学习网络的深度对最后的分类和识别的效果有着很大的影响,所以正常想法就是能把网络设计的越深越好, 但是事实上却不是这样,常规的网络的堆叠(plain netw ...

  2. 深度学习目标检测 RCNN F-RCNN SPP yolo-v1 v2 v3 残差网络ResNet MobileNet SqueezeNet ShuffleNet

    深度学习目标检测--结构变化顺序是RCNN->SPP->Fast RCNN->Faster RCNN->YOLO->SSD->YOLO2->Mask RCNN ...

  3. 残差网络ResNet网络原理及实现

    全文共1483字,5张图,预计阅读时间10分钟. 作者介绍: 石晓文,中国人民大学信息学院在读研究生,美团外卖算法实习生 简书ID:石晓文的学习日记(https://www.jianshu.com/u ...

  4. CNN经典网络之残差网络(ResNet)剖析

    残差网络(Residual Network, ResNet)是在2015年继AlexNet.VGG.GoogleNet 三个经典的CNN网络之后提出的,并在ImageNet比赛classificati ...

  5. (pytorch-深度学习)实现残差网络(ResNet)

    实现残差网络(ResNet) 我们一般认为,增加神经网络模型的层数,充分训练后的模型理论上能更有效地降低训练误差. 理论上,原模型解的空间只是新模型解的空间的子空间.也就是说,如果我们能将新添加的层训 ...

  6. dlibdotnet 人脸相似度源代码_使用dlib中的深度残差网络(ResNet)实现实时人脸识别 - supersayajin - 博客园...

    opencv中提供的基于haar特征级联进行人脸检测的方法效果非常不好,本文使用dlib中提供的人脸检测方法(使用HOG特征或卷积神经网方法),并使用提供的深度残差网络(ResNet)实现实时人脸识别 ...

  7. 残差网络ResNet

    文章目录 ResNet模型 两个注意点 关于x 关于残差单元 核心实验 原因分析 ResNet的效果 题外话 ResNet是由何凯明在论文Deep Residual Learning for Imag ...

  8. 对残差网络resnet shortcut的解释

    重读残差网络--resnet(对百度vd模型解读) 往事如yan 已于 2022-02-25 07:53:37 修改 652 收藏 4 分类专栏: AI基础 深度学习概念 文章标签: 网络 cnn p ...

  9. 吴教授的CNN课堂:进阶 | 从LeNet到残差网络(ResNet)和Inception Net

    转载自:https://www.jianshu.com/p/841ac51c7961 第二周是关于卷积网络(CNN)进阶部分,学到挺多新东西.因为之前了解过CNN基础后,就大多在用RNN进行自然语言处 ...

最新文章

  1. Silverlight C# 游戏开发:Silverlight开发环境
  2. 教育部:建设100+AI特色专业,500万AI人才缺口要补上!
  3. dede列表分页php,dede列表页分页英文调用方法
  4. Effective C# 原则1:尽可能的使用属性(property),而不是数据成员(field)
  5. 如何利用 AI 对抗疫情?
  6. 如何用苹果手机生成扫描件
  7. 大牛书单 | 腾讯运维大咖陪你过724
  8. 云+X案例展 | 金融类:青云QingCloud助力泰康人寿云计算演进之路
  9. 摄影灵感|轮廓趋势,剪影以一种主要的方式回来了。
  10. 网络安全基础——破解系统密码
  11. 计算机天空之城音乐谱,天谕手游天空之城乐谱代码是什么
  12. 幸福加油站(EAP)——忙碌的心里意义
  13. Python 编程案例:谁没交论文?输出并生成电子表格
  14. 中职计算机图形图像课程标准,计算机图形与图形图像处理技术的相互结合
  15. 2021年制冷与空调设备运行操作模拟试题及制冷与空调设备运行操作模拟考试
  16. Httpwatch网盘下载
  17. 服务器维护中 verycd,强大的VeryCD服务器终于挂了...
  18. 2023款MacBook Pro M2参数配置怎么样 性能怎么样 尺寸重量多少?
  19. 第四章 SpringCloud Alibaba (一)微服务环境搭建
  20. 利用Abaqus的UMAT子程序仿真木材蠕变现象

热门文章

  1. python雷达图数据_PYTHON绘制雷达图代码实例
  2. java 接口参数验证_SpringBoot实现通用的接口参数校验
  3. IC卡读卡器web开发,支持IE,Chrome,Firefox,Safari,Opera等主流浏览 器
  4. 安卓的自定义的DemoApplication 出现的问题。
  5. Swift - 访问通讯录联系人(使用系统提供的通讯录交互界面)
  6. JPA(二)之CRUD操作
  7. 用WDM开发USB驱动程序
  8. WPF Multi-Touch 开发:高级触屏操作(Manipulation)
  9. 离职交接文档_如何写好离职工作交接文档?
  10. python中mid_使用Python进行新浪微博的mid和url互相转换实例(10进制和62进制互算)...