【问题标题】:How to visualize attention weights?如何可视化注意力权重?
【发布时间】:2019-05-20 21:31:38
【问题描述】:

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 文件中。

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

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

【问题讨论】:

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


    【解决方案1】:

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

    (...)
    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 笔记本,则以下 sn-p 可帮助您理解概念并进行可视化:

    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 并可视化。我希望它很清楚。

    【讨论】:

    • 在这种情况下,我们如何为额外的输出模拟额外的损失函数
    【解决方案2】:

    model = Model([input_], [output, attention_weights]) 返回模型 预测,attention_weights = model.predict(val_x, batch_size = 192)

    【讨论】:

    • 请编辑您的答案并正确格式化您的代码。未缩进的 Python 代码并没有真正的帮助。
    猜你喜欢
    • 2022-07-02
    • 2017-03-28
    • 2020-02-09
    • 1970-01-01
    • 2021-07-27
    • 2019-12-03
    • 2019-02-08
    • 1970-01-01
    • 2018-02-02
    相关资源
    最近更新 更多