Tensorflow实例分析Google Inception v3 网络

本文直接从Inception v3的代码实现入手,分析其中值得借鉴的思想



首先要知道一个slim的组件,可以给参数自动赋值,可以省去很多操作

def inception_arg_scope(weight_decay=0.00004,
                        use_batch_norm=True,
                        batch_norm_decay=0.9997,
                        batch_norm_epsilon=0.001):
  """Defines the default arg scope for inception models.
  Args:
    weight_decay: 设置L2正则
    use_batch_norm: 设置是否使用batch normalization
    batch_norm_decay: BN的衰减系数
    batch_norm_epsilon: 为了避免除数为0加的一个小型浮点数

  Returns:
    An `arg_scope` to use for the inception models.
  """
  batch_norm_params = {
      'decay': batch_norm_decay,
      'epsilon': batch_norm_epsilon,
      'updates_collections': tf.GraphKeys.UPDATE_OPS,
  }
  if use_batch_norm:
    normalizer_fn = slim.batch_norm
    normalizer_params = batch_norm_params
  else:
    normalizer_fn = None
    normalizer_params = {}
  # 下面这句会对conv2d和全连接层这两个函数的weights_regularizer参数自动赋值为
  with slim.arg_scope([slim.conv2d, slim.fully_connected],
                      weights_regularizer=slim.l2_regularizer(weight_decay)):
    #接下来再嵌套一个slim.arg_scope,对conv2d的权重、激活函数、正则化函数及其参数自动赋值后将其返回 
    with slim.arg_scope(
        [slim.conv2d],
        weights_initializer=slim.variance_scaling_initializer(),
        activation_fn=tf.nn.relu,
        normalizer_fn=normalizer_fn,
        normalizer_params=normalizer_params) as sc:
      return sc
该函数的的作用就是事先定义好conv2d中的各种参数,之后再定义卷积层就会非常方便。


trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)
再定义一个用于产生截断分布的函数


接下来定义inception v3 base,它可以生成inception v3的卷积部分

def inception_v3_base(inputs,
                      final_endpoint='Mixed_7c',
                      min_depth=16,
                      depth_multiplier=1.0,
                      scope=None):
  """Inception model from http://arxiv.org/abs/1512.00567.

  总体名称对应结构如下
  Old name          | New name
  =======================================
  conv0             | Conv2d_1a_3x3
  conv1             | Conv2d_2a_3x3
  conv2             | Conv2d_2b_3x3
  pool1             | MaxPool_3a_3x3
  conv3             | Conv2d_3b_1x1
  conv4             | Conv2d_4a_3x3
  pool2             | MaxPool_5a_3x3
  mixed_35x35x256a  | Mixed_5b
  mixed_35x35x288a  | Mixed_5c
  mixed_35x35x288b  | Mixed_5d
  mixed_17x17x768a  | Mixed_6a
  mixed_17x17x768b  | Mixed_6b
  mixed_17x17x768c  | Mixed_6c
  mixed_17x17x768d  | Mixed_6d
  mixed_17x17x768e  | Mixed_6e
  mixed_8x8x1280a   | Mixed_7a
  mixed_8x8x2048a   | Mixed_7b
  mixed_8x8x2048b   | Mixed_7c

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    final_endpoint: specifies the endpoint to construct the network up to. It
      can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3',
      'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3',
      'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c',
      'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c'].
    min_depth: Minimum depth value (number of channels) for all convolution ops.
      Enforced when depth_multiplier < 1, and not an active constraint when
      depth_multiplier >= 1.
    depth_multiplier: Float multiplier for the depth (number of channels)
      for all convolution ops. The value must be greater than zero. Typical
      usage will be to set this value in (0, 1) to reduce the number of
      parameters or computation cost of the model.
    scope: Optional variable_scope.

  Returns:
    tensor_out: output tensor corresponding to the final_endpoint.
    end_points: a set of activations for external use, for example summaries or
                losses.

  Raises:
    ValueError: if final_endpoint is not set to one of the predefined values,
                or depth_multiplier <= 0
  """
  # end_points will collect relevant activations for external use, for example
  # summaries or losses.
  end_points = {}

  if depth_multiplier <= 0:
    raise ValueError('depth_multiplier is not greater than zero.')
  #用来计算深度的函数,与乘子结合
  depth = lambda d: max(int(d * depth_multiplier), min_depth)
  
  with tf.variable_scope(scope, 'InceptionV3', [inputs]):
    with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],
                        stride=1, padding='VALID'):
      # 299 x 299 x 3
      end_point = 'Conv2d_1a_3x3'
      net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point)
      end_points[end_point] = net
      if end_point == final_endpoint: return net, end_points
      # 149 x 149 x 32
      end_point = 'Conv2d_2a_3x3'
      net = slim.conv2d(net, depth(32), [3, 3], scope=
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TensorFlow提供了一个丰富的深度学习模型库,包括ResNet和Inception模型。由于ResNet和Inception具有不同的架构和特点,我们可以结合它们来提高模型的性能。 ResNet是一个非常深的卷积神经网络模型,它解决了深层网络难以训练的问题,通过引入残差连接使得网络可以更容易地训练和优化。ResNet有多个版本,其中ResNet18是相对较轻量级的版本,适用于一些资源受限的场景。 而InceptionGoogle提出的一种模块化的卷积神经网络架构,通过同时执行多个不同尺度的卷积操作,有效地捕捉到图像中不同尺度的特征信息,从而提高了模型的性能和泛化能力。 要将ResNet18与Inception相结合,可以通过在ResNet18的基础上添加Inception模块来扩展网络的能力。具体做法是在ResNet18的最后几个残差模块之后添加一个或多个Inception模块,以引入Inception的多尺度特征表示能力。 在TensorFlow中,可以使用tf.keras来构建模型。首先,我们可以通过加载ResNet18的预训练模型来获得ResNet18的基础结构,然后在其结构的合适位置插入Inception模块。具体实现如下: ```python import tensorflow as tf # 加载ResNet18的预训练模型 resnet18_model = tf.keras.applications.ResNet18(weights='imagenet', include_top=False) # 在ResNet18的最后一个残差模块之后添加Inception模块 x = resnet18_model.output # 添加自定义的Inception模块 # ... # 构建新的模型 model = tf.keras.Model(inputs=resnet18_model.input, outputs=x) ``` 在上述代码中,通过加载ResNet18的预训练模型并指定参数`include_top=False`来获得ResNet18的基础结构。然后,将这个结构的输出作为新模型的输入,然后在适当的位置添加自定义的Inception模块。最后,构建一个新的模型,将ResNet18的输入和Inception模块的输出作为模型的输入和输出。 通过这种方式,我们可以将ResNet18和Inception结合起来,从而充分利用它们各自的优势,提高模型在图像分类等任务中的性能。当然,在实际应用中,还需要根据具体任务的需求进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值