【问题标题】:LSTM in Keras: Number of parameters differs between sequential and functional APIKeras 中的 LSTM:顺序 API 和功能 API 之间的参数数量不同
【发布时间】:2019-03-16 11:38:12
【问题描述】:

使用顺序 API

如果我使用 Keras 的 Sequential API 创建一个 LSTM,代码如下:

from keras.models import Sequential
from keras.layers import LSTM

model = Sequential()
model.add(LSTM(2, input_dim=3))

然后

model.summary()

返回48个参数,如this Stack Overflow question所示即可。

快速详情:

input_dim = 3, output_dim = 2
n_params = 4 * output_dim * (output_dim + input_dim + 1) = 4 * 2 * (2 + 3 + 1) = 48

使用函数式 API

但如果我使用以下代码对功能 API 执行相同操作:

from keras.models import Model
from keras.layers import Input
from keras.layers import LSTM

inputs = Input(shape=(3, 1))
lstm = LSTM(2)(inputs)
model = Model(input=inputs, output=lstm)

然后

model.summary()

返回 32 个参数。

为什么会有这样的差异?

【问题讨论】:

    标签: python machine-learning keras lstm recurrent-neural-network


    【解决方案1】:

    不同之处在于,当您将input_dim=x 传递给RNN 层(包括LSTM 层)时,这意味着输入形状为(None, x),即有不同数量的时间步长,其中每个时间步长都是长度为x 的向量.但是,在函数式 API 示例中,您将 shape=(3, 1) 指定为输入形状,这意味着有 3 个时间步长,每个时间步长都有一个特征。因此参数的数量将是:4 * output_dim * (output_dim + input_dim + 1) = 4 * 2 * (2 + 1 + 1) = 32,这是模型摘要中显示的数字。

    此外,如果您使用 Keras 2.x.x,则在为 RNN 层使用 input_dim 参数时会收到警告:

    UserWarning:input_diminput_length 参数在循环中 层已弃用。请改用input_shape

    用户警告:更新您对 Keras 2 API 的 LSTM 调用:LSTM(2, input_shape=(None, 3))

    【讨论】:

    • 如果在功能 API 中,我将 inputs = Input(shape=(3, 1)) 替换为 inputs = Input(shape=(1, 3 )),我得到了 48 个参数,正如预期的那样。谢谢!
    【解决方案2】:

    我是这样解决的:

    Case 1:
    m (input) = 3
    n (output) = 2
    
    params = 4 * ( (input * output) + (output ^ 2) + output)
           = 4 * (3*2 + 2^2 + 2)
           = 4 * (6 + 4 + 2)
           = 4 * 12
           = 48
    
    
    
    Case 2:
    m (input) = 1
    n (output) = 2
    
    params = 4 * ( (input * output) + (output ^ 2) + output)
           = 4 * (1*2 + 2^2 + 2)
           = 4 * (2 + 4 + 2)
           = 4 * 8
           = 32
    

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多