Skip to content

Add legend for visualize_text #403

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

Closed
wants to merge 9 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)))