keras 神经网络模型 Sequential模型

789 阅读2分钟

Sequential模型,就是多个网络层的线性堆叠。它建立模型有两中方式,一种是向layer中添加list,一种是通.add()的方式一层层的天添加。



  • from
    keras.models
    import
    Sequential



  • from
    keras.layers.core
    import
    Dense,Activation



  • #list方式




  • model = Sequential([Dense(
    32
    ,input_dim=
    784
    ),Activation(
    'relu'
    ),Dense(
    10
    ),Activation(
    'softmax'
    )])



  • #.add的方式




  • model = Sequential()



  • model.add(Dense(input_dim=
    3
    ,output_dim=
    10
    ))



  • model.add(Activation(
    'relu'
    ))


Dense层,是常用的全连接层,

Dense(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)

各参数的含义:

  • units:大于0的整数,代表该层的输出维度。

  • activation:激活函数,为预定义的激活函数名(参考),或逐元素(element-wise)的Theano函数。如果不指定该参数,将不会使用任何激活函数(即使用线性激活函数:a(x)=x)

  • use_bias: 布尔值,是否使用偏置项

  • kernel_initializer:权值初始化方法,为预定义初始化方法名的字符串,或用于初始化权重的初始化器。参考

  • bias_initializer:偏置向量初始化方法,为预定义初始化方法名的字符串,或用于初始化偏置向量的初始化器。参考

  • kernel_regularizer:施加在权重上的正则项,为对象

  • bias_regularizer:施加在偏置向量上的正则项,为对象

  • activity_regularizer:施加在输出上的正则项,为对象

  • kernel_constraints:施加在权重上的约束项,为对象

  • bias_constraints:施加在偏置上的约束项,为对象



输入

形如(batch_size, ..., input_dim)的nD张量,最常见的情况为(batch_size, input_dim)的2D张量

输出

形如(batch_size, ..., units)的nD张量,最常见的情况为(batch_size, units)的2D张量

Activation层

激活层对一个层的输出施加激活函数,激活函数可以通过设置单独的实现,也可以在构造层对象时通过传递activation参数实现



  • from
    keras.layers
    import
    Activation, Dense







  • model.add(Dense(
    64
    ))



  • model.add(Activation(
    'tanh'
    ))



  • #等价于




  • model.add(Dense(
    64
    , activation=
    'tanh'
    ))



  • #也可以通过传递一个逐元素运算的Theano/TensorFlow/CNTK函数来作为激活函数:




  • from
    keras
    import
    backend
    as
    K







  • def tanh(x):



  • return
    K.tanh(x)







  • model.add(Dense(
    64
    , activation=tanh))



  • model.add(Activation(tanh))


激活函数

  • softmax:对输入数据的最后一维进行softmax

  • elu

  • selu

  • softplus

  • softsign

  • relu

  • tanh

  • sigmoid

  • hard_sigmoid

  • linear

更多免费技术资料可关注:annalin1203