基于Theano的深度学习(Deep Learning)框架Keras学习随笔-12-核心层

来源:互联网 发布:网页压缩减肥软件 编辑:程序博客网 时间:2024/05/16 07:20

       本文来自CSDN博客:http://blog.csdn.net/niuwei22007/article/details/49277595  原博客可以获取更多文章

       从这篇开始介绍Keras的Layers,就是构成网络的每一层。Keras实现了很多层,包括核心层、卷基层、RNN网络层等诸多常用的网络结构。下面开介绍核心层中包含了哪些内容。因为这个核心层我现在还没有全部用到,所以会有一部分内容我并不是十分了解,因此直接附带了原文档介绍。希望有了解的博友指点一二。

一、核心层基类

keras.layers.core.Layer()

       下面介绍一下该类中包含的几个基本方法。 

#  把previous_layer层的输出连接到当前层的输入set_previous(previous_layer)

       返回:None
       参数

  •        previous_layer : Layer对象

# 获取某层网络的输出get_output(train)

       返回:Theano tensor

       参数

  •        train : Boolean. 指定是在训练模式下还是测试模型下计算该层的输出。Specifies whether output iscomputed in training mode or in testing mode, which can change the logic, forinstance in there are any Dropout layers in the network.

# 获取某层网络的输入get_input(train)

       返回:Theano tensor

       参数

  •        train : 同上。

 # 获取网络的权值get_weights()

       返回:一个numpy array组成的list,每一层的参数值是一个numpy array

# 设置网络权值参数set_weights(weights)

       参数

  •        weights : 一个numpy array组成的list,每一层的权值是一个numpy array,且该list中的元素顺序要与get_weights(self)中返回的一致。(就是对应好每一层,不要打乱了顺序)

get_config()

       返回:描述网络的配置信息字典。

 二、Dense(标准的一维全连接层)

keras.layers.core.Dense(output_dim,init='glorot_uniform', activation='linear', weights=NoneW_regularizer=None, b_regularizer=None, activity_regularizer=None,W_constraint=None, b_constraint=None, input_dim=None)

       inputshape: 2维 tensor(nb_samples, input_dim)

       outputshape: 2维 tensor(nb_samples, output_dim)

       参数

  •        output_dim: int >= 0,输出结果的维度
  •        init : 初始化权值的函数名称或Theano function。可以使用Keras内置的(内置初始化权值函数见这里),也可以传递自己编写的Theano function。如果不给weights传递参数时,则该参数必须指明。
  •        activation : 激活函数名称或者Theano function。可以使用Keras内置的(内置激活函数见这里),也可以是传递自己编写的Theano function。如果不明确指定,那么将没有激活函数会被应用。
  •        weights :用于初始化权值的numpy arrays组成的list。这个List至少有1个元素,其shape为input_dim, output_dim。(如果指定init了,那么weights可以赋值None)
  •        W_regularizer:权值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        b_regularizer:偏置值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        activity_regularizer:网络输出的规则化项,必须传入一个ActivityRegularizer的实例(详细的内置规则化见这里)。
  •        W_constraint:权值约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        b_constraint:偏置约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        input_dim:输入数据的维度。这个参数会在模型的第一层中用到。 

三、TimeDistributedDense

keras.layers.core.TimeDistributedDense(output_dim,init='glorot_uniform', activation='linear', weights=NoneW_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None,input_dim=None, input_length=None)

       这是一个基于时间维度的全连接层。主要就是用来构建RNN(递归神经网络)的,但是在构建RNN时需要设置return_sequences=True

       inputshape: 3维 tensor(nb_samples, timesteps,input_dim)

       参数

  •        output_dim: int >= 0,输出结果的维度
  •        init : 初始化权值的函数名称或Theano function。可以使用Keras内置的(内置初始化权值函数见这里),也可以传递自己编写的Theano function。如果不给weights传递参数时,则该参数必须指明。
  •        activation : 激活函数名称或者Theano function。可以使用Keras内置的(内置激活函数见这里),也可以是传递自己编写的Theano function。如果不明确指定,那么将没有激活函数会被应用。
  •        weights :用于初始化权值的numpy arrays组成的list。这个List至少有1个元素,其shape为input_dim, output_dim。(如果指定init了,那么weights可以赋值None)
  •        W_regularizer:权值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        b_regularizer:偏置值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        activity_regularizer:网络输出的规则化项,必须传入一个ActivityRegularizer的实例(详细的内置规则化见这里)。
  •        W_constraint:权值约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        b_constraint:偏置约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        input_dim:输入数据的维度。这个参数会在模型的第一层中用到。
  •        input_length:Length of input sequences, whenit is constant. This argument is required if you are going to connect Flattenthen Dense layers upstream (without it, the shape of the dense outputs cannotbe computed).

       简单举例

# input shape: (nb_samples, timesteps,10)model.add(LSTM(5, return_sequences=True, input_dim=10)) # output shape: (nb_samples, timesteps, 5)model.add(TimeDistributedDense(15)) # output shape:(nb_samples, timesteps, 15)

四、AutoEncoder

keras.layers.core.AutoEncoder(encoder, decoder,output_reconstruction=True, weights=None)

       这是一个用于构建很常见的自动编码模型。如果参数output_reconstruction=True,那么dim(input)=dim(output);否则dim(output)=dim(hidden)

       inputshape: 取决于encoder的定义

       outputshape:取决于decoder的定义

       参数

  •        encoder:编码器,是一个layer类型或layer容器类型。
  •        decoder:解码器,是一个layer类型或layer容器类型。
  •        output_reconstruction:boolean。值为False时,调用predict()函数时,输出是经过最深隐层的激活函数。Otherwise, the output of thefinal decoder layer is presented. Be sure your validation data conforms to thislogic if you decide to use any.(这一块还不太了解,待以后了解了再补充)
  •        weights:用于初始化权值的numpy arrays组成的list。这个List至少有1个元素,其shape为input_dim, output_dim

       简单举例

from keras.layers import containers # input shape: (nb_samples, 32)encoder =containers.Sequential([Dense(16, input_dim=32), Dense(8)])decoder =containers.Sequential([Dense(16, input_dim=8), Dense(32)]) autoencoder =Sequential()autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder,output_reconstruction=False))

 五、Activation

keras.layers.core.Activation(activation)

       Apply an activation function tothe input.(貌似是把激活函数应用到输入数据的一种层结构)

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape:同input shape

       参数

  •        activation:编码器,是一个layer类型或layer容器类型。
  •        decoder:解码器,是一个layer类型或layer容器类型。
  •        output_reconstruction:boolean。值为False时,调用predict()函数时,输出是经过最深隐层的激活函数。Otherwise, the output of thefinal decoder layer is presented. Be sure your validation data conforms to thislogic if you decide to use any.(这一块还不太了解,待以后了解了再补充)
  •        weights:激活函数名称或者Theano function。可以使用Keras内置的(内置激活函数见这里),也可以是传递自己编写的Theano function。如果不明确指定,那么将没有激活函数会被应用。

六、Dropout

keras.layers.core.Dropout(p)

       Dropout的意思就是训练和预测时随机减少特征个数,即去掉输入数据中的某些维度,用于防止过拟合。通过设置Dropout中的参数p,在训练和预测模型的时候,每次更新都会丢掉(总数*p)个特征,以达到防止过拟合的目的。可以参考:Dropout: A Simple Way to PreventNeural Networks from Overfitting

         强烈推荐看一下文章《理解dropout》,可以使你更充分的理解dropout。

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape:同input shape

       参数

  •        p:float(0≤p<1),每次训练要丢弃特征的比例。

七、Reshape

keras.layers.core.Reshape(dims)

       就是把输入数据的shape重新reshape一下,原数据保持不变。

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape(nb_samples, dims)

       参数

       dims:整数型元组,新的shape。

       简单举例

# input shape: (nb_samples, 10)model.add(Dense(100, input_dim=10)) # output shape: (nb_samples, 100)model.add(Reshape(dims=(10, 10)))  # output shape: (nb_samples, 10, 10) 

八、Flatten

keras.layers.core.Flatten()

       把多维输入转换为1维输入,名字很形象,就是把输入给压平了。

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape(nb_samples,nb_input_units)

 九、RepeatVector

keras.layers.core.RepeatVector(n)

       把1维的输入重复n次。假设输入维度为(nb_samples, dim),那么输出shape就是(nb_samples, n, dim)

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape(nb_samples,nb_input_units)

       参数

  •        n:int,重复n次 

十、Permute

keras.layers.core.Permute(dims)

       根据给定的元组交换输入数据维度。主要是用于RNNs和Convnets。

       inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。

       outputshape:和input shape一样。但是维度需要根据指定的元组顺序重新排序。

       参数:元组,明确指出交换对象。例如(2,1)就是交换输入的第一维和第二维。

       简单举例

# input shape: (nb_samples, 10)model.add(Dense(50, input_dim=10)) # output shape: (nb_samples, 50)model.add(Reshape(dims=(10, 5))) # output shape:(nb_samples, 10, 5)model.add(Permute(dims=(2, 1))) #output shape: (nb_samples, 5, 10)

十一、ActivityRegularization

keras.layers.core.ActivityRegularization(l1=0., l2=0.)

       保持输入不变,在代价函数基础上增加一项针对input activity的L1和L2规则化项。

       这个层的可以用来降低前一层激活函数结果的稀疏性。

 十二、MaxoutDense

keras.layers.core.MaxoutDense(output_dim,nb_feature=4, init='glorot_uniform', weights=None,W_regularizer=None, b_regularizer=None, activity_regularizer=None,W_constraint=None, b_constraint=None, input_dim=None)

       A dense maxout layer. AMaxoutDense layer takes the element-wise maximum of nb_feature Dense(input_dim, output_dim) linear layers. This allows thelayer to learn a convex, piecewise linear activation function over the inputs.See this paper for more details. Note that this is a linear layer -- if youwish to apply activation function (you shouldn't need to -- they are universalfunction approximators), an Activation layer must be added after.

       inputshape:2维tensor,shape为(nb_samples, input_dim)

       outputshape:2维tensor,shape为(nb_samples, output_dim)

  •        output_dim : int >= 0
  •        nb_feature : int >= 0. the number of features tocreate for the maxout. This is equivalent to the number of piecewise elementsto be allowed for the activation function.。
  •        init: 初始化权值的函数名称或Theano function。可以使用Keras内置的(内置初始化权值函数见这里),也可以传递自己编写的Theano function。如果不给weights传递参数时,则该参数必须指明。
  •        weights: 用于初始化权值的numpy arrays组成的list。这个List至少有1个元素,其shape为input_dim, output_dim。(如果指定init了,那么weights可以赋值None)
  •        W_regularizer:权值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        b_regularizer:偏置值的规则化项,必须传入一个WeightRegularizer的实例(比如L1或L2规则化项,详细的内置规则化见这里)。
  •        activity_regularizer:网络输出的规则化项,必须传入一个ActivityRegularizer的实例(详细的内置规则化见这里)。
  •        W_constraint:权值约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        b_constraint:偏置约束,必须传入一个constraints的实例(详细的约束限制见这里)。
  •        input_dim:输入数据的维度。这个参数会在模型的第一层中用到。

       简单举例

# input shape: (nb_samples, 10)model.add(Dense(100, input_dim=10)) # output shape: (nb_samples, 100)model.add(MaxoutDense(50, nb_feature=10)) # output shape: (nb_samples, 50)

十三、Merge

keras.layers.core.Merge(models, mode='sum')

       把layers(or containers) list合并为一个层,用以下三种模式中的一种:summul concat

       参数

  •        layers : list of layers or containers.
  •        mode : String. {‘sum’ , ‘mul’ , ‘concat’}中的一种。其中summul是对待合并层输出做一个简单的求和、乘积运算,因此要求待合并层输出shape要一致。concat是将待合并层输出沿着最后一个维度进行拼接,因此要求待合并层输出只有最后一个维度不同。

       简单举例

left = Sequential()left.add(Dense(50, input_shape=(784,)))left.add(Activation('relu')) right = Sequential()right.add(Dense(50, input_shape=(784,)))right.add(Activation('relu')) model = Sequential()model.add(Merge([left,right], mode='sum')) model.add(Dense(10))model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') model.fit([X_train, X_train], Y_train, batch_size=128, nb_epoch=20, validation_data=([X_test, X_test], Y_test))

 十四、Masking

keras.layers.core.Masking(mask_value=0.)

       Create a mask for the input databy usingmask_value as the sentinel value whichshould be masked out. Given an input of dimensions(nb_samples,timesteps, input_dim), return the input untouched as output, and supply a maskof shape (nb_samples, timesteps)where all timesteps which hadall their values equal to mask_value are masked out.

       inputshape: 3D tensor with shape: (nb_samples, timesteps,features).

       outputshape: 3D tensor with shape:(nb_samples, timesteps,features).

 

参考资料:

  •  官方教程
  • 理解dropout

0 0