在使用注意力机制碰到的问题,困扰许久
1、目前普通的注意力机制在scdn查看时碰到两种写法,在对时间维度的注意力应用中,一个是博主自写的,代码如下;另一种是项目中直接导入attention包的做法。非常疑惑是否一致,以及该博主的代码是否正确,感谢回复。
def attention_3d_block(inputs):
# inputs.shape = (batch_size, time_steps, input_dim)
input_dim = int(inputs.shape[2])
a = Permute((2, 1))(inputs)
a = Reshape((input_dim, TIME_STEPS))(a) # this line is not useful. It's just to know which dimension is what.
a = Dense(TIME_STEPS, activation='softmax')(a)
if SINGLE_ATTENTION_VECTOR:
a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)
a = RepeatVector(input_dim)(a)
a_probs = Permute((2, 1), name='attention_vec')(a)
output_attention_mul = merge([inputs, a_probs], name='attention_mul', mode='mul')
return output_attention_mul
2、同样,问题一提到的项目中使用方法如下,该方法是对时间的注意力应用还是维度层面的应用,如何去看呢
num_samples, time_steps, input_dim, output_dim = 100, 10, 1, 1
data_x = np.random.uniform(size=(num_samples, time_steps, input_dim))
data_y = np.random.uniform(size=(num_samples, output_dim))
model_input = Input(shape=(time_steps, input_dim))
x = LSTM(64, return_sequences=True)(model_input)
x = Attention(units=32)(x)
x = Dense(1)(x)
model = Model(model_input, x)
model.compile(loss='mae', optimizer='adam')
3、同样是问题一的博主编写的对于维度的注意力应用,代码如下,想知道这样是否可行呢。
def attention_3d_block(inputs):
input_dim = int(inputs.shape[2])
a = inputs
a = Dense(input_dim, activation='softmax')(a)
if SINGLE_ATTENTION_VECTOR:
a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)
a = RepeatVector(input_dim)(a)
a_probs = Permute((1, 2), name='attention_vec')(a)
output_attention_mul = merge([inputs, a_probs], name='attention_mul', mode='mul')
return output_attention_mul
4、如果我有一个多维度多时间步的数据,我希望对维度层面和时间步层面都进行注意力应用,目前看到的一个结构是在编码器使用空间注意力,解码器使用时间注意力,具体的模型结构应该是怎样呢,Input-空间注意力-lstm-时间注意力-output吗
感谢各位的回复。