我使用(keras-self-attention)在KERAS中实现attention LSTM。在训练了模型之后,我如何将注意力部分形象化?这是一个时间序列预测案例。在
from keras.models import Sequential
from keras_self_attention import SeqWeightedAttention
from keras.layers import LSTM, Dense, Flatten
model = Sequential()
model.add(LSTM(activation = 'tanh' ,units = 200, return_sequences = True,
input_shape = (TrainD[0].shape[1], TrainD[0].shape[2])))
model.add(SeqSelfAttention())
model.add(Flatten())
model.add(Dense(1, activation = 'relu'))
model.compile(optimizer = 'adam', loss = 'mse')
一种方法是获取给定输入的
SeqSelfAttention
的输出,并对它们进行组织,以便显示每个通道的预测结果(见下文)。要了解更高级的内容,请查看iNNvestigate library(包括使用示例)。在说明:
show_features_1D
获取layer_name
(可以是一个子串)层输出并显示每个通道的预测(标记),时间步长沿x轴,输出值沿y轴。input_data
=单批形状(1, input_shape)
prefetched_outputs
=已经获得层输出;覆盖input_data
max_timesteps
=要显示的最大时间步数max_col_subplots
=沿水平方向的子批次的最大值equate_axes
=强制所有x轴和y轴相等(建议用于公平比较)show_y_zero
=是否将y=0显示为红线channel_axis
=层特征维度(例如units
对于LSTM,这是最后一个)scale_width, scale_height
=缩放显示的图像宽度和高度dpi
=图像质量(每英寸点数)视觉效果(如下)说明:
print(outs_1)
会发现所有的量值都很小,变化不大,所以包括y=0点和等分轴会产生一条直线状的视觉效果,这可以解释为自我注意是偏向性的。在batch_shape
而不是input_shape
定义模型会删除打印形状中的所有?
,我们可以看到第一个输出的形状是(10, 60, 240)
,第二个输出的形状是(10, 240, 240)
。换句话说,第一个输出返回LSTM channel attention,第二个输出返回“timesteps attention”。下面的热图结果可以解释为显示注意“冷却”w.r.t.时间步数。在SeqWeightedAttention更容易可视化,但没有太多可可视化的;您需要去掉上面的})。在
Flatten
才能使其工作。然后注意力的输出形状变成(10, 60)
和(10, 240)
-对于这两个形状,可以使用一个简单的直方图plt.hist
(只需确保排除批处理维度,即feed(60,)
或{^{pr2}$
SeqWeightedAttention示例每个请求:
相关问题 更多 >
编程相关推荐