Views
No views yet
negative vs neutral vs positive.1# !pip install transformers sentencepiece --quiet
2import torch
3from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
5model_checkpoint = 'cointegrated/rubert-tiny-sentiment-balanced'
6tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
7model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint)
8if torch.cuda.is_available():
9 model.cuda()
10
11def get_sentiment(text, return_type='label'):
12 """ Calculate sentiment of a text. `return_type` can be 'label', 'score' or 'proba' """
13 with torch.no_grad():
14 inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True).to(model.device)
15 proba = torch.sigmoid(model(**inputs).logits).cpu().numpy()[0]
16 if return_type == 'label':
17 return model.config.id2label[proba.argmax()]
18 elif return_type == 'score':
19 return proba.dot([-1, 0, 1])
20 return proba
21
22text = 'Какая гадость эта ваша заливная рыба!'
23# classify the text
24print(get_sentiment(text, 'label')) # negative
25# score the text on the scale from -1 (very negative) to +1 (very positive)
26print(get_sentiment(text, 'score')) # -0.5894946306943893
27# calculate probabilities of all labels
28print(get_sentiment(text, 'proba')) # [0.7870447 0.4947824 0.19755007]| Source | Macro F1 |
|---|---|
| SentiRuEval2016_banks | 0.83 |
| SentiRuEval2016_tele | 0.74 |
| kaggle_news | 0.66 |
| linis | 0.50 |
| mokoron | 0.98 |
| rureviews | 0.72 |
| rusentiment | 0.67 |