如何可视化注意权重?

时间:2018-12-20 11:00:13

标签: keras deep-learning nlp rnn attention-model

Using this implementation 我对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文件中。

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

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

1 个答案:

答案 0 :(得分:2)

可视化注意力并不复杂,但是您需要一些技巧。在构建模型时,您需要给您的注意力层起一个名字。

(...)
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或hex并进行可视化处理。我希望一切都清楚。

相关问题