如何可视化注意力权重?

问题描述 投票:0回答:2

使用此实现 我已将注意力纳入我的 RNN(将输入序列分为两类),如下所示。

visible = Input(shape=(250,))

embed=Embedding(vocab_size,100)(visible)

activations= keras.layers.GRU(250, return_sequences=True)(embed)

attention = TimeDistributed(Dense(1, activation='tanh'))(activations) 
attention = Flatten()(attention)
attention = Activation('softmax')(attention)
attention = RepeatVector(250)(attention)
attention = Permute([2, 1])(attention) 

sent_representation = keras.layers.multiply([activations, attention])
sent_representation = Lambda(lambda xin: K.sum(xin, axis=1))(sent_representation)
predictions=Dense(1, activation='sigmoid')(sent_representation)

model = Model(inputs=visible, outputs=predictions)

我已经训练了模型并将权重保存到

weights.best.hdf5
文件中。

我正在处理二元分类问题,模型的输入是一个热向量(基于字符)。

如何可视化当前实现中某些特定测试用例的注意力权重?

keras deep-learning nlp recurrent-neural-network attention-model
2个回答
21
投票

可视化注意力并不复杂,但你需要一些技巧。在构建模型时,您需要为注意力层命名。

(...)
attention = keras.layers.Activation('softmax', name='attention_vec')(attention)
(...)

加载保存的模型时,您需要在预测时获取注意层输出。

model = load_model("./saved_model.h5")
model.summary()
model = Model(inputs=model.input,
              outputs=[model.output, model.get_layer('attention_vec').output])

现在您可以获得模型的输出以及注意力向量。

ouputs = model.predict(encoded_input_text)
model_outputs = outputs[0]
attention_outputs = outputs[1]

注意力向量的可视化方法有很多。基本上,注意力输出是一个 softmax 输出,它们在 0 和 1 之间。您可以将这些值更改为 rgb 代码。如果您正在使用 Jupyter 笔记本,以下代码片段可以帮助您理解概念并进行可视化:

class CharVal(object):
    def __init__(self, char, val):
        self.char = char
        self.val = val

    def __str__(self):
        return self.char

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb
def color_charvals(s):
    r = 255-int(s.val*255)
    color = rgb_to_hex((255, r, r))
    return 'background-color: %s' % color

# if you are using batches the outputs will be in batches
# get exact attentions of chars
an_attention_output = attention_outputs[0][-len(encoded_input_text):]

# before the prediction i supposed you tokenized text
# you need to match each char and attention
char_vals = [CharVal(c, v) for c, v in zip(tokenized_text, attention_output)]
import pandas as pd
char_df = pd.DataFrame(char_vals).transpose()
# apply coloring values
char_df = char_df.style.applymap(color_charvals)
char_df

总而言之,您需要从模型中获取注意力输出,将输出与输入进行匹配,并将它们转换为 RGB 或十六进制并进行可视化。我希望它是清楚的。


-2
投票
model = Model([input_], [output, attention_weights])
return model
predictions, attention_weights = model.predict(val_x, batch_size = 192)
© www.soinside.com 2019 - 2024. All rights reserved.