Skip to content

Instantly share code, notes, and snippets.

@choyan
Created August 5, 2021 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choyan/d7ddc506742193b0c1856cbab93d223f to your computer and use it in GitHub Desktop.
Save choyan/d7ddc506742193b0c1856cbab93d223f to your computer and use it in GitHub Desktop.
# import libraries
import pandas as pd
import seaborn as sns
import flair
# configure size of heatmap
sns.set(rc={'figure.figsize':(35,3)})
# function to visualize
def visualise_sentiments(data):
sns.heatmap(pd.DataFrame(data).set_index("Sentence").T,center=0, annot=True, cmap = "PiYG")
# model
flair_sentiment = flair.models.TextClassifier.load('en-sentiment')
# text
sentence = "To inspire and guide entrepreneurs is where I get my joy of contribution"
# sentiment
s = flair.data.Sentence(sentence)
flair_sentiment.predict(s)
total_sentiment = s.labels
total_sentiment
# tokenize sentiments
tokens = [token.text for token in s.tokens]
ss = [flair.data.Sentence(s) for s in tokens]
[flair_sentiment.predict(s) for s in ss]
sentiments = [s.labels[0].score * (-1,1)[str(s.labels[0]).split()[0].startswith("POS")] for s in ss]
# heatmap
visualise_sentiments({
"Sentence":["SENTENCE"] + tokens,
"Sentiment":[total_sentiment[0].score *(-1,1)[str(total_sentiment[0]).split()[0].startswith("POS")]] + sentiments,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment