Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add legend for visualize_text #403

Closed
wants to merge 9 commits into from
21 changes: 20 additions & 1 deletion captum/attr/_utils/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,9 @@ def format_word_importances(words, importances):
return "".join(tags)


def visualize_text(datarecords: Iterable[VisualizationDataRecord]) -> None:
def visualize_text(
datarecords: Iterable[VisualizationDataRecord], legend: bool = True
) -> None:
assert HAS_IPYTHON, (
"IPython must be available to visualize text. "
"Please run 'pip install ipython'."
Expand Down Expand Up @@ -543,6 +545,23 @@ def visualize_text(datarecords: Iterable[VisualizationDataRecord]) -> None:
)
)

if legend:
dom.append(
'<div style="border-top: 1px solid; margin-top: 5px; \
padding-top: 5px; display: inline-block">'
)
dom.append("<b>Legend: </b>")

for value, label in zip([-1, 0, 1], ["Negative", "Neutral", "Positive"]):
dom.append(
'<span style="display: inline-block; width: 10px; height: 10px; \
border: 1px solid; background-color: \
{value}"></span> {label} '.format(
value=_get_color(value), label=label
)
)
dom.append("</div>")

dom.append("".join(rows))
dom.append("</table>")
display(HTML("".join(dom)))