Skip to content

Instantly share code, notes, and snippets.

@ihsgnef
Last active January 17, 2024 02:01
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ihsgnef/f13c35cd46624c8f458a4d23589ac768 to your computer and use it in GitHub Desktop.
Save ihsgnef/f13c35cd46624c8f458a4d23589ac768 to your computer and use it in GitHub Desktop.
Visualize attention over text with background colors
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def colorize(words, color_array):
# words is a list of words
# color_array is an array of numbers between 0 and 1 of length equal to words
cmap = matplotlib.cm.get_cmap('RdBu')
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])
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))
s = colorize(words, color_array)
# to display in ipython notebook
from IPython.display import display, HTML
display(HTML(s))
# or simply save in an html file and open in browser
with open('colorize.html', 'w') as f:
f.write(s)
@binshengliu
Copy link

Thanks for sharing. It's very useful. Just keeping a note that the color map can be found at Choosing Colormaps in Matplotlib.

@Avi-avidan
Copy link

thanks guys. loved it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment