Flair: How to turn predicted label from flair.data.Label into int?

Created on 17 Apr 2019  路  3Comments  路  Source: flairNLP/flair

classifier.predict(sentence) followed by sentence.labels outputs a label object. For example
"[1 (1.0)]"
The type of item inside the list is "flair.data.Label"

How can I extract the values 1 and 1.0 to int, string or other familiar datatype, from the Label-object?

sentence.labels:
[1 (1.0)]

type(sentence.labels)
list

type(sentence.labels[0])
flair.data.Label

Type: Label
String form: 1 (1.0)
File: .../site-packages/flair/data.py
Docstring:
This class represents a label of a sentence. Each label has a value and optionally a confidence score. The
score needs to be between 0.0 and 1.0. Default value for the score is 1.0.

Update
I now found, there is a method .to_dict()

This seems to do it

sentence.labels[0].to_dict()
{'value': '1', 'confidence': 1.0}

sentence.labels[0].to_dict()['value']
'1'

sentence.labels[0].to_dict()['confidence']
1.0

And they are in types of str and float.

question

Most helpful comment

Hello @jannenev the Label object has two fields in Flair 0.4.1, namely value and score that you can directly access. I.e. you can do:

sentence.labels[0].value
sentence.labels[0].score

You can also iterate through all labels and print value and score for each:

for label in sentence.labels:
    print(label)
    print(label.value)
    print(label.score)

All 3 comments

I think the last time I did use the classifier output and get an int was with label = str(sentence.labels[0]).split()[0]

This seems to do it

sentence.labels[0].to_dict()
{'value': '1', 'confidence': 1.0}

sentence.labels[0].to_dict()['value']
'1'

sentence.labels[0].to_dict()['confidence']
1.0

And they are in types of str and float.

Hello @jannenev the Label object has two fields in Flair 0.4.1, namely value and score that you can directly access. I.e. you can do:

sentence.labels[0].value
sentence.labels[0].score

You can also iterate through all labels and print value and score for each:

for label in sentence.labels:
    print(label)
    print(label.value)
    print(label.score)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Y4rd13 picture Y4rd13  路  3Comments

UrszulaCzerwinska picture UrszulaCzerwinska  路  3Comments

aschmu picture aschmu  路  3Comments

shoarora picture shoarora  路  3Comments

ciaochiaociao picture ciaochiaociao  路  3Comments