Commit
·
c302b1e
1
Parent(s):
ac5da21
Create functions.py
Browse files- functions.py +30 -0
functions.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoConfig, AutoModelForSequenceClassification
|
2 |
+
from scipy.special import softmax
|
3 |
+
# Define the preprocess function
|
4 |
+
def preprocess(text):
|
5 |
+
new_text = []
|
6 |
+
for t in text.split(" "):
|
7 |
+
t = '@user' if t.startswith('@') and len(t) > 1 else t
|
8 |
+
t = 'http' if t.startswith('http') else t
|
9 |
+
new_text.append(t)
|
10 |
+
return " ".join(new_text)
|
11 |
+
|
12 |
+
# Define the sentiment_analysis function
|
13 |
+
def sentiment_analysis(text, tokenizer, model):
|
14 |
+
text = preprocess(text)
|
15 |
+
encoded_input = tokenizer(text, return_tensors='pt')
|
16 |
+
output = model(**encoded_input)
|
17 |
+
scores_ = output[0][0].detach().numpy()
|
18 |
+
scores_ = softmax(scores_)
|
19 |
+
labels = ['Negative', 'Positive']
|
20 |
+
scores = {l: float(s) for (l, s) in zip(labels, scores_)}
|
21 |
+
return scores
|
22 |
+
|
23 |
+
# Define the map_sentiment_score_to_rating function
|
24 |
+
def map_sentiment_score_to_rating(score):
|
25 |
+
min_score = 0.0
|
26 |
+
max_score = 1.0
|
27 |
+
min_rating = 1
|
28 |
+
max_rating = 10
|
29 |
+
rating = ((score - min_score) / (max_score - min_score)) * (max_rating - min_rating) + min_rating
|
30 |
+
return rating
|