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

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根据层名称来初始化网络就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • keras中的backend.clip用法

    如下所示: keras.backend.clip(x, min_value, max_value) 逐元素clip(将超出指定范围的数强制变为边界值) 参数 x: 张量或变量. min_value: Python 浮点或整数. max_value: Python 浮点或整数. 返回 一个张量. import tensorflow as tf from keras import backend a = tf.constant(2.1) #定义tensor常量 b = backend.clip(a,

  • keras中的卷积层&池化层的用法

    卷积层 创建卷积层 首先导入keras中的模块 from keras.layers import Conv2D 卷积层的格式及参数: Conv2D(filters, kernel_size, strides, padding, activation='relu', input_shape) filters: 过滤器数量 kernel_size:指定卷积窗口的高和宽的数字 strides: 卷积stride,如果不指定任何值,则strides设为1 padding: 选项包括'valid'和'sa

  • 使用Keras预训练模型ResNet50进行图像分类方式

    Keras提供了一些用ImageNet训练过的模型:Xception,VGG16,VGG19,ResNet50,InceptionV3.在使用这些模型的时候,有一个参数include_top表示是否包含模型顶部的全连接层,如果包含,则可以将图像分为ImageNet中的1000类,如果不包含,则可以利用这些参数来做一些定制的事情. 在运行时自动下载有可能会失败,需要去网站中手动下载,放在"~/.keras/models/"中,使用WinPython则在"settings/.ke

  • 在keras下实现多个模型的融合方式

    在网上搜过发现关于keras下的模型融合框架其实很简单,奈何网上说了一大堆,这个东西官方文档上就有,自己写了个demo: # Function:基于keras框架下实现,多个独立任务分类 # Writer: PQF # Time: 2019/9/29 import numpy as np from keras.layers import Input, Dense from keras.models import Model import tensorflow as tf # 生成训练集 data

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

    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) a

  • 关于Keras Dense层整理

    我就废话不多说了,大家还是直接看代码吧! ''' Created on 2018-4-4 ''' keras.layers.core.Dense( units, #代表该层的输出维度 activation=None, #激活函数.但是默认 liner use_bias=True, #是否使用b kernel_initializer='glorot_uniform', #初始化w权重,keras/initializers.py bias_initializer='zeros', #初始化b权重 k

  • 解决Keras 自定义层时遇到版本的问题

    在2.2.0版本前, from keras import backend as K from keras.engine.topology import Layer class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # 为该层

  • 给keras层命名,并提取中间层输出值,保存到文档的实例

    更新: 感谢评论区提供的方案. 采用model.summary(),model.get_config()和for循环均可获得Keras的层名. 示例如下图 对于keras特定层的命名,只需在层内添加 name 即可 model.add(Activation('softmax',name='dense_1') ) # 注意 name 要放于函数内 #提取中间层 from keras.models import Model import keras layer_name = 'dense_1' #获

  • keras之权重初始化方式

    在神经网络训练中,好的权重 初始化会加速训练过程. 下面说一下kernel_initializer 权重初始化的方法. 不同的层可能使用不同的关键字来传递初始化方法,一般来说指定初始化方法的关键字是kernel_initializer 和 bias_initializer model.add(Dense(64, kernel_initializer=initializers.random_normal(stddev=0.01))) # also works; will use the defau

  • keras实现基于孪生网络的图片相似度计算方式

    我就废话不多说了,大家还是直接看代码吧! import keras from keras.layers import Input,Dense,Conv2D from keras.layers import MaxPooling2D,Flatten,Convolution2D from keras.models import Model import os import numpy as np from PIL import Image from keras.optimizers import S

  • keras训练曲线,混淆矩阵,CNN层输出可视化实例

    训练曲线 def show_train_history(train_history, train_metrics, validation_metrics): plt.plot(train_history.history[train_metrics]) plt.plot(train_history.history[validation_metrics]) plt.title('Train History') plt.ylabel(train_metrics) plt.xlabel('Epoch')

  • keras 自定义loss层+接受输入实例

    loss函数如何接受输入值 keras封装的比较厉害,官网给的例子写的云里雾里, 在stackoverflow找到了答案 You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function). def custom_loss_wrapper(input_

  • 解决Keras的自定义lambda层去reshape张量时model保存出错问题

    前几天忙着参加一个AI Challenger比赛,一直没有更新博客,忙了将近一个月的时间,也没有取得很好的成绩,不过这这段时间内的确学到了很多,就在决赛结束的前一天晚上,准备复现使用一个新的网络UPerNet的时候出现了一个很匪夷所思,莫名其妙的一个问题.谷歌很久都没有解决,最后在一个日语网站上看到了解决方法. 事后想想,这个问题在后面搭建网络的时候会很常见,但是网上却没有人提出解决办法,So, I think that's very necessary for me to note this.

  • Keras自定义实现带masking的meanpooling层方式

    Keras确实是一大神器,代码可以写得非常简洁,但是最近在写LSTM和DeepFM的时候,遇到了一个问题:样本的长度不一样.对不定长序列的一种预处理方法是,首先对数据进行padding补0,然后引入keras的Masking层,它能自动对0值进行过滤. 问题在于keras的某些层不支持Masking层处理过的输入数据,例如Flatten.AveragePooling1D等等,而其中meanpooling是我需要的一个运算.例如LSTM对每一个序列的输出长度都等于该序列的长度,那么均值运算就只应该

随机推荐