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

To visualize attention: color tokens using attention weights

我有一系列标记,每个标记都有一个注意力权重。现在,我想使用特定颜色的阴影来可视化令牌。例如,蓝色阴影,根据权重从最浅到最深。

我知道可以 。但是,如何做到这一点 show/print token/word?

  1. 要在文件中打印,需要使用特殊的文件格式。例如html
  2. this and 启发,以下代码将根据给定的权重打印具有不同 intensity/shades 蓝色的文本。

    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')
        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)
    

    输出: