可视化注意力:使用注意力权重标记颜色

时间:2019-12-06 21:21:46

标签: python matplotlib deep-learning visualization colormap

我有一系列记号,每个记号都有注意权重。现在,我想使用特定颜色的阴影来可视化令牌。例如,基于权重的蓝色阴影从最亮到最暗。

我知道可以draw a line or curve that creates shades。但是,如何显示/打印令牌/单词?

1 个答案:

答案 0 :(得分:1)

  1. 要打印文件,需要使用特殊的文件格式。例如html
  2. thisthis的激励,以下代码将根据给定的权重以不同的强度/蓝色阴影打印文本。

    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    
    def colorize(words, color_array):
        cmap=matplotlib.cm.Blues
        template = '<span class="barcode"; style="color: black; background-color: {}">{}</span>'
        colored_string = ''
        for word, color in zip(words, color_array):
            color = matplotlib.colors.rgb2hex(cmap(color)[:3])
            print(color)
            colored_string += template.format(color, '&nbsp' + word + '&nbsp')
        [![enter image description here][3]][3]return colored_string
    
    words = 'The quick brown fox jumps over the lazy dog'.split()
    color_array = np.random.rand(len(words))
    
    print(color_array)
    s = colorize(words, color_array)
    
    # or simply save in an html file and open in browser
    with open('colorize.html', 'w') as f:
        f.write(s)
    

    输出: enter image description here