使用keras根据层名称来初始化网络


Posted in Python onMay 21, 2020

keras根据层名称来初始化网络

def get_model(input_shape1=[75, 75, 3], input_shape2=[1], weights=None):
 bn_model = 0
 trainable = True
 # kernel_regularizer = regularizers.l2(1e-4)
 kernel_regularizer = None
 activation = 'relu'

 img_input = Input(shape=input_shape1)
 angle_input = Input(shape=input_shape2)

 # Block 1
 x = Conv2D(64, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block1_conv1')(img_input)
 x = Conv2D(64, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block1_conv2')(x)
 x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)

 # Block 2
 x = Conv2D(128, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block2_conv1')(x)
 x = Conv2D(128, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block2_conv2')(x)
 x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)

 # Block 3
 x = Conv2D(256, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block3_conv1')(x)
 x = Conv2D(256, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block3_conv2')(x)
 x = Conv2D(256, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block3_conv3')(x)
 x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)

 # Block 4
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block4_conv1')(x)
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block4_conv2')(x)
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block4_conv3')(x)
 x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)

 # Block 5
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block5_conv1')(x)
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block5_conv2')(x)
 x = Conv2D(512, (3, 3), activation=activation, padding='same',
    trainable=trainable, kernel_regularizer=kernel_regularizer,
    name='block5_conv3')(x)
 x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)

 branch_1 = GlobalMaxPooling2D()(x)
 # branch_1 = BatchNormalization(momentum=bn_model)(branch_1)

 branch_2 = GlobalAveragePooling2D()(x)
 # branch_2 = BatchNormalization(momentum=bn_model)(branch_2)

 branch_3 = BatchNormalization(momentum=bn_model)(angle_input)

 x = (Concatenate()([branch_1, branch_2, branch_3]))
 x = Dense(1024, activation=activation, kernel_regularizer=kernel_regularizer)(x)
 # x = Dropout(0.5)(x)
 x = Dense(1024, activation=activation, kernel_regularizer=kernel_regularizer)(x)
 x = Dropout(0.6)(x)
 output = Dense(1, activation='sigmoid')(x)

 model = Model([img_input, angle_input], output)
 optimizer = Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=1e-8, decay=0.0)
 model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])

 if weights is not None:
  # 将by_name设置成True
  model.load_weights(weights, by_name=True)
  # layer_weights = h5py.File(weights, 'r')
  # for idx in range(len(model.layers)):
  #  model.set_weights()
 print 'have prepared the model.'

 return model

补充知识:keras.layers.Dense()方法

keras.layers.Dense()是定义网络层的基本方法,执行的操作是:output = activation(dot(input,kernel)+ bias。

其中activation是激活函数,kernel是权重矩阵,bias是偏向量。如果层输入大于2,在进行初始点积之前会将其展平。

代码如下:

class Dense(Layer):
 """Just your regular densely-connected NN layer.
 `Dense` implements the operation:
 `output = activation(dot(input, kernel) + bias)`
 where `activation` is the element-wise activation function
 passed as the `activation` argument, `kernel` is a weights matrix
 created by the layer, and `bias` is a bias vector created by the layer
 (only applicable if `use_bias` is `True`).
 Note: if the input to the layer has a rank greater than 2, then
 it is flattened prior to the initial dot product with `kernel`.
 # Example
 ```python
  # as first layer in a sequential model:
  model = Sequential()
  model.add(Dense(32, input_shape=(16,)))
  # now the model will take as input arrays of shape (*, 16)
  # and output arrays of shape (*, 32)
  # after the first layer, you don't need to specify
  # the size of the input anymore:
  model.add(Dense(32))
 ```
 # Arguments
  units: Positive integer, dimensionality of the output space.
  activation: Activation function to use
   (see [activations](../activations.md)).
   If you don't specify anything, no activation is applied
   (ie. "linear" activation: `a(x) = x`).
  use_bias: Boolean, whether the layer uses a bias vector.
  kernel_initializer: Initializer for the `kernel` weights matrix
   (see [initializers](../initializers.md)).
  bias_initializer: Initializer for the bias vector
   (see [initializers](../initializers.md)).
  kernel_regularizer: Regularizer function applied to
   the `kernel` weights matrix
   (see [regularizer](../regularizers.md)).
  bias_regularizer: Regularizer function applied to the bias vector
   (see [regularizer](../regularizers.md)).
  activity_regularizer: Regularizer function applied to
   the output of the layer (its "activation").
   (see [regularizer](../regularizers.md)).
  kernel_constraint: Constraint function applied to
   the `kernel` weights matrix
   (see [constraints](../constraints.md)).
  bias_constraint: Constraint function applied to the bias vector
   (see [constraints](../constraints.md)).
 # Input shape
  nD tensor with shape: `(batch_size, ..., input_dim)`.
  The most common situation would be
  a 2D input with shape `(batch_size, input_dim)`.
 # Output shape
  nD tensor with shape: `(batch_size, ..., units)`.
  For instance, for a 2D input with shape `(batch_size, input_dim)`,
  the output would have shape `(batch_size, units)`.
 """
 
 @interfaces.legacy_dense_support
 def __init__(self, units,
     activation=None,
     use_bias=True,
     kernel_initializer='glorot_uniform',
     bias_initializer='zeros',
     kernel_regularizer=None,
     bias_regularizer=None,
     activity_regularizer=None,
     kernel_constraint=None,
     bias_constraint=None,
     **kwargs):
  if 'input_shape' not in kwargs and 'input_dim' in kwargs:
   kwargs['input_shape'] = (kwargs.pop('input_dim'),)
  super(Dense, self).__init__(**kwargs)
  self.units = units
  self.activation = activations.get(activation)
  self.use_bias = use_bias
  self.kernel_initializer = initializers.get(kernel_initializer)
  self.bias_initializer = initializers.get(bias_initializer)
  self.kernel_regularizer = regularizers.get(kernel_regularizer)
  self.bias_regularizer = regularizers.get(bias_regularizer)
  self.activity_regularizer = regularizers.get(activity_regularizer)
  self.kernel_constraint = constraints.get(kernel_constraint)
  self.bias_constraint = constraints.get(bias_constraint)
  self.input_spec = InputSpec(min_ndim=2)
  self.supports_masking = True
 
 def build(self, input_shape):
  assert len(input_shape) >= 2
  input_dim = input_shape[-1]
 
  self.kernel = self.add_weight(shape=(input_dim, self.units),
          initializer=self.kernel_initializer,
          name='kernel',
          regularizer=self.kernel_regularizer,
          constraint=self.kernel_constraint)
  if self.use_bias:
   self.bias = self.add_weight(shape=(self.units,),
          initializer=self.bias_initializer,
          name='bias',
          regularizer=self.bias_regularizer,
          constraint=self.bias_constraint)
  else:
   self.bias = None
  self.input_spec = InputSpec(min_ndim=2, axes={-1: input_dim})
  self.built = True
 
 def call(self, inputs):
  output = K.dot(inputs, self.kernel)
  if self.use_bias:
   output = K.bias_add(output, self.bias)
  if self.activation is not None:
   output = self.activation(output)
  return output
 
 def compute_output_shape(self, input_shape):
  assert input_shape and len(input_shape) >= 2
  assert input_shape[-1]
  output_shape = list(input_shape)
  output_shape[-1] = self.units
  return tuple(output_shape)
 
 def get_config(self):
  config = {
   'units': self.units,
   'activation': activations.serialize(self.activation),
   'use_bias': self.use_bias,
   'kernel_initializer': initializers.serialize(self.kernel_initializer),
   'bias_initializer': initializers.serialize(self.bias_initializer),
   'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
   'bias_regularizer': regularizers.serialize(self.bias_regularizer),
   'activity_regularizer': regularizers.serialize(self.activity_regularizer),
   'kernel_constraint': constraints.serialize(self.kernel_constraint),
   'bias_constraint': constraints.serialize(self.bias_constraint)
  }
  base_config = super(Dense, self).get_config()
  return dict(list(base_config.items()) + list(config.items()))

参数说明如下:

units:正整数,输出空间的维数。

activation: 激活函数。如果未指定任何内容,则不会应用任何激活函数。即“线性”激活:a(x)= x)。

use_bias:Boolean,该层是否使用偏向量。

kernel_initializer:权重矩阵的初始化方法。

bias_initializer:偏向量的初始化方法。

kernel_regularizer:权重矩阵的正则化方法。

bias_regularizer:偏向量的正则化方法。

activity_regularizer:输出层正则化方法。

kernel_constraint:权重矩阵约束函数。

bias_constraint:偏向量约束函数。

以上这篇使用keras根据层名称来初始化网络就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之开始真正编程
Sep 12 Python
python计算文本文件行数的方法
Jul 06 Python
在Django的上下文中设置变量的方法
Jul 20 Python
详解python读取和输出到txt
Mar 29 Python
使用虚拟环境打包python为exe 文件的方法
Aug 29 Python
python进程池实现的多进程文件夹copy器完整示例
Nov 27 Python
浅析python,PyCharm,Anaconda三者之间的关系
Nov 27 Python
简单介绍django提供的加密算法
Dec 18 Python
Pytorch之view及view_as使用详解
Dec 31 Python
在python3中实现查找数组中最接近与某值的元素操作
Feb 29 Python
pytorch 实现变分自动编码器的操作
May 24 Python
Python还能这么玩之只用30行代码从excel提取个人值班表
Jun 05 Python
关于Keras Dense层整理
May 21 #Python
Django如何使用redis作为缓存
May 21 #Python
如何打包Python Web项目实现免安装一键启动的方法
May 21 #Python
keras之权重初始化方式
May 21 #Python
Python3 ID3决策树判断申请贷款是否成功的实现代码
May 21 #Python
Python使用os.listdir和os.walk获取文件路径
May 21 #Python
keras 权重保存和权重载入方式
May 21 #Python
You might like
php实现文件下载功能的几个代码分享
2014/05/10 PHP
PHP.ini安全配置检测工具pcc简单介绍
2015/07/02 PHP
WordPress中用于获取搜索表单的PHP函数使用解析
2016/01/05 PHP
在laravel中实现ORM模型使用第二个数据库设置
2019/10/24 PHP
用jQuery简化JavaScript开发分析
2009/02/19 Javascript
javascript基础之查找元素的详细介绍(访问节点)
2013/07/05 Javascript
javascript实现淡蓝色的鼠标拖动选择框实例
2015/05/09 Javascript
javascript单页面手势滑屏切换原理详解
2016/03/21 Javascript
jQuery中ztree 点击文本框弹出下拉框的实例代码
2017/02/05 Javascript
微信小程序使用Promise简化回调
2018/02/06 Javascript
Vue 使用 Mint UI 实现左滑删除效果CellSwipe
2018/04/27 Javascript
Vue 中axios配置实例详解
2018/07/27 Javascript
JS高级技巧(简洁版)
2018/07/29 Javascript
怎么理解wx.navigateTo的events参数使用详情
2020/05/18 Javascript
Javascript生成器(Generator)的介绍与使用
2021/01/31 Javascript
[52:06]完美世界DOTA2联赛决赛日 Inki vs LBZS 第一场 11.08
2020/11/10 DOTA
python实现在pickling的时候压缩的方法
2014/09/25 Python
Python TestCase中的断言方法介绍
2019/05/02 Python
python爬虫项目设置一个中断重连的程序的实现
2019/07/26 Python
Django 反向生成url实例详解
2019/07/30 Python
Python中的上下文管理器相关知识详解
2019/09/19 Python
pytorch 数据处理:定义自己的数据集合实例
2019/12/31 Python
python GUI库图形界面开发之PyQt5 UI主线程与耗时线程分离详细方法实例
2020/02/26 Python
django model通过字典更新数据实例
2020/04/01 Python
Python面向对象多态实现原理及代码实例
2020/09/16 Python
基于python的opencv图像处理实现对斑马线的检测示例
2020/11/29 Python
对CSS3选择器的研究(详解)
2016/09/16 HTML / CSS
SportsDirect.com新加坡:英国第一体育零售商
2019/03/30 全球购物
实现strstr功能,即在父串中寻找子串首次出现的位置
2016/08/05 面试题
知识竞赛活动方案
2014/02/18 职场文书
人力资源本科毕业生求职信
2014/06/04 职场文书
销售员岗位职责
2014/06/09 职场文书
大学生第一学年自我鉴定
2014/09/12 职场文书
2016春季校长开学典礼致辞
2015/11/26 职场文书
Win11开始菜单添加休眠选项
2022/04/19 数码科技
vue 数字翻牌器动态加载数据
2022/04/20 Vue.js