问题描述
我在为时间序列样本中的所有时间步长应用相同的 dropout 掩码时遇到了一个棘手的问题,以便 LSTM 层在一次前向传递中看到相同的输入。我阅读了多篇文章,但没有找到解决方案。以下 implementation 是否支持这一点?或者这会在每个时间步随机丢弃不同的特征图?
dim = (420,48,1) # grayscale images of size 48x48
inputShape = (dim)
Input_words = Input(shape=inputShape,name='input_vid')
x = Timedistributed(Conv2D(filters=50,kernel_size=(8,8),padding='same',activation='relu'))(Input_words)
x = Timedistributed(MaxPooling2D(pool_size=(2,2)))(x)
x = Timedistributed(SpatialDropout2D(0.2))(x)
x = Timedistributed(Batchnormalization())(x)
x = Timedistributed(Flatten())(x)
x = LSTM(200,dropout=0.2,recurrent_dropout=0.2)(x)
out = Dense(5,activation='softmax')(x)
model = Model(inputs=Input_words,outputs=[out])
opt = Adam(lr=1e-3,decay=1e-3 / 200)
model.compile(loss = 'categorical_crossentropy',optimizer=opt,metrics = ['accuracy'])
如果不是,在 keras 上有什么好的解决方案?我可以使用 Dropout with noise_shape 来解决我的问题吗?
解决方法
您可以简单地自行测试所有可能性...
我们生成一个形状样本(1、n_frame、H、W、n_channel)并可视化不同丢弃策略的影响:
inputShape = (100,8,1) # frames of 100 grayscale images of size 8x8
X = np.random.uniform(1,2,(1,)+inputShape).astype('float32') # generate 1 sample
layer = Dropout(0.4,seed=0)
d = layer(X,training=True).numpy()
layer = Dropout(0.4,seed=0,noise_shape=(X.shape[0],1,X.shape[2],X.shape[3],X.shape[4]))
d1d = layer(X,training=True).numpy()
layer = TimeDistributed(SpatialDropout2D(0.4,seed=0))
tsd2d = layer(X,training=True).numpy()
layer = SpatialDropout3D(0.4,seed=0)
# the same as:
# layer = Dropout(0.4,X.shape[4]))
sd3d = layer(X,training=True).numpy()
来自Dropout
的结果:
plt.figure(figsize=(15,12))
for i,f_map in enumerate(d[0]):
if i == 12:
break
plt.subplot(3,4,i+1)
plt.imshow(np.squeeze(f_map>0,-1),vmin=0,vmax=1)
plt.title(f"frame {i}")
来自 Dropout
和 noise_shape
的结果:
plt.figure(figsize=(15,f_map in enumerate(d1d[0]):
if i == 12:
break
plt.subplot(3,vmax=1)
plt.title(f"frame {i}")
来自 TimeDistributed
加 SpatialDropout2D
的结果
plt.figure(figsize=(15,f_map in enumerate(tsd2d[0]):
if i == 12:
break
plt.subplot(3,vmax=1)
plt.title(f"frame {i}")
来自SpatialDropout3D
的结果:
plt.figure(figsize=(15,12))
for i,f_map in enumerate(sd3d[0]):
if i == 12:
break
plt.subplot(3,vmax=1)
plt.title(f"frame {i}")
结论
- 简单的
Dropout
在没有规则的情况下随机丢弃每一帧中的像素 -
Dropout
withnoise_shape
随机丢弃每帧中始终在相同位置的像素 -
TimeDistributed
加SpatialDropout2D
随机丢弃整帧 -
SpatialDropout3D
丢弃随机通道中的所有帧