Flair: How to make the predict (or sentence.labels) output the top-n labels?

Created on 26 Jun 2019  路  4Comments  路  Source: flairNLP/flair

Hey, I've been trying to make a recommender system for which I need the output as the top-5 predicted labels? How do I do this using the predict/sentence.labels functionality? Also, the sentence.labels outputs the label and it's probability. I just want to make a list of the labels that it has predicted. How do I do this?

question

Most helpful comment

@ParthJawale1996 I think you can achieve this with:

from flair.data import Sentence
from flair.models import TextClassifier

classifier = TextClassifier.load('en-sentiment')
sentence = Sentence('I like Munich .')

classifier.predict(sentence, multi_class_prob=True)

This should output:

[POSITIVE (0.8669394850730896), NEGATIVE (0.13306047022342682)]

:)

For top_n (where n is your desired value) just do:

top_n = 5
print(sentence.labels[:top_n])

All 4 comments

@alanakbik @stefan-it My data does NOT have multiple labels for a single data point, but I still want the labels and scores for the top 5. Any suggestions?
I think you've referred to it here, but how do I actually go about getting them?
https://github.com/zalandoresearch/flair/issues/745#issuecomment-495199700

Basically, I was hoping to get a list of the top-5 predicted labels.

@ParthJawale1996 I think you can achieve this with:

from flair.data import Sentence
from flair.models import TextClassifier

classifier = TextClassifier.load('en-sentiment')
sentence = Sentence('I like Munich .')

classifier.predict(sentence, multi_class_prob=True)

This should output:

[POSITIVE (0.8669394850730896), NEGATIVE (0.13306047022342682)]

:)

For top_n (where n is your desired value) just do:

top_n = 5
print(sentence.labels[:top_n])

@stefan-it Here how do i index only the score or only the labels?

Thanks in advance.

Got it, prediction.value and prediction.score.

Thanks anyways.

Was this page helpful?
0 / 5 - 0 ratings