基于这篇文章。我需要一些基本的实施帮助。下面你会看到我使用 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
层实现代码:
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)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句