【问题标题】:how to obtain the runtime batch size of a Keras model如何获取 Keras 模型的运行时批量大小
【发布时间】:2018-06-15 10:20:55
【问题描述】:

基于this post。我需要一些基本的实施帮助。下面你会看到我的模型使用了 Dropout 层。使用noise_shape 参数时,碰巧最后一批不适合批量大小,从而产生错误(参见其他帖子)。

原模型:

def LSTM_model(X_train,Y_train,dropout,hidden_units,MaskWert,batchsize):
   model = Sequential()
   model.add(Masking(mask_value=MaskWert, input_shape=(X_train.shape[1],X_train.shape[2]) ))
   model.add(Dropout(dropout, noise_shape=(batchsize, 1, X_train.shape[2]) ))   
   model.add(Dense(hidden_units, activation='sigmoid', kernel_constraint=max_norm(max_value=4.) ))   
   model.add(LSTM(hidden_units, return_sequences=True, dropout=dropout, recurrent_dropout=dropout))  

现在 Alexandre Passos 建议使用 tf.shape 获取运行时批处理大小。我尝试以不同的方式将运行时批量大小的想法实现到 Keras 中,但从未奏效。

   import Keras.backend as K

   def backend_shape(x):
       return K.shape(x)

   def LSTM_model(X_train,Y_train,dropout,hidden_units,MaskWert,batchsize):    
       batchsize=backend_shape(X_train)
       model = Sequential()
       ...
       model.add(Dropout(dropout, noise_shape=(batchsize[0], 1, X_train.shape[2]) )) 
       ...  

但这只是给了我输入张量形状,而不是运行时输入张量形状。

我也尝试过使用 Lambda 层

def output_of_lambda(input_shape):
   return (input_shape)

def LSTM_model_2(X_train,Y_train,dropout,hidden_units,MaskWert,batchsize):       
   model = Sequential()
   model.add(Lambda(output_of_lambda, outputshape=output_of_lambda))
   ...
   model.add(Dropout(dropout, noise_shape=(outputshape[0], 1, X_train.shape[2]) )) 

还有不同的变体。但正如您已经猜到的那样,这根本不起作用。 模型定义实际上是正确的地方吗? 您能否给我一个提示或更好地告诉我如何获得 Keras 模型的运行批量大小?非常感谢。

【问题讨论】:

  • dropout 层已经使用了运行时批处理形状code 如果你给它None 并使用K.shape 提取它,实际错误是什么?
  • 亲爱的 nuric,当我使用时间序列时,我想修复所有时间步的丢失 (batch_size,1,features) 。是否可以将内部运行时批处理形状与时间步长和特征的设置结合使用? (?,1 个特征) 。也许还要检查第一行中链接的先前post 以获得更清晰的图片。

标签: keras runtime layer


【解决方案1】:

当前的实现确实会根据运行时批量大小进行调整。来自Dropout层实现code

symbolic_shape = K.shape(inputs)
noise_shape = [symbolic_shape[axis] if shape is None else shape
               for axis, shape in enumerate(self.noise_shape)]

因此,如果您提供noise_shape=(None, 1, features),形状将按照上述代码为 (runtime_batchsize, 1, features)。

【讨论】:

  • 亲爱的主,这很容易。非常感谢 Nuric,你救了我一个不眠之夜。
猜你喜欢
  • 2022-12-20
  • 2021-05-22
  • 1970-01-01
  • 2016-05-05
  • 2020-02-11
  • 2011-12-31
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多