How to set the sentiment attribute on a Span?

Viewed 212

I'm trying thhe Keras example from spacy documentation, but instead of suming the sentiment score in the Doc like that

for sent, label in zip(sentences, ys):
  sent.doc.sentiment += label - 0.5

I would like to keep the score on the sentence level like that

for sent, label in zip(sentences, ys):
  sent.sentiment = float(label)

This code give me that error

AttributeError: attribute 'sentiment' of 'spacy.tokens.span.Span' objects is not writable

Is there a setter to call instead? I tried set_sentiment without success. Am I missing something? Is it a bug?

1 Answers

You can find the implementation of Span.sentiment here. You can see it is indeed not writable, because it either looks up the value in self.doc.user_span_hooks, or takes the average of token.sentiment for the tokens in that span.

[EDITED BELOW]

The sentiment of a Token is not context-dependent though. It uses the information present in the underlying Lexeme. That means that any word, such as "love", would have the same sentiment value in any sentence/context.

So there's two things you can do: either write to the sentiment of the lexemes like so:

vocab["love"].sentiment = 3.0

Or implement a custom hook that allows you to define any function you want. You can do this on the span (doc.user_span_hooks) or token (doc.user_token_hooks) level:

doc.user_span_hooks["sentiment"] = lambda span: 10.0
Related