-
Notifications
You must be signed in to change notification settings - Fork 0
/
review_sentiment.py
112 lines (88 loc) · 3.62 KB
/
review_sentiment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# -*- coding: utf-8 -*-
"""Review sentiment.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1KJJbg4V-8S1VFHqaj8RT3G-0TJr4ADyz
"""
import pandas as pd
import numpy as np
dataset = pd.read_csv("Reviews.csv")
dataset.head()
def f(row):
if row['Score']>=1 and row['Score']<=3:
val = 0
else:
val = 1
return val
dataset['sentiment']= dataset.apply(f,axis = 1)
dataset['sentiment'].value_counts()
grouped = dataset.groupby(dataset.sentiment)
sample_1=grouped.get_group(1)
sample_0 = grouped.get_group(0)
sample_1['sentiment'].value_counts()
sample_1 = sample_1.sample(frac = 0.29)
sample_1['sentiment'].value_counts()
sample_1['sentiment'].value_counts()
frames = [sample_1,sample_0]
last_version_dataset = pd.concat(frames)
last_version_dataset['sentiment'].value_counts()
df = last_version_dataset.sample(frac = 0.1)
df.isnull().sum()
df = df.dropna()
df.isnull().sum()
from transformers import pipeline
generator = pipeline(task = "text-generation")
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
model = AutoModelForCausalLM.from_pretrained("distilgpt2")
better_generator = pipeline(task = "text-generation",model = model, tokenizer = tokenizer)
from sklearn.model_selection import train_test_split
from transformers import DistilBertForSequenceClassification, TrainingArguments, Trainer, DistilBertTokenizerFast
tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
labels = df['sentiment']
texts = df['Text']
#Splitting dataset into training and test
train_texts, test_texts, train_labels, test_labels = train_test_split(texts, labels, test_size=.3)
#Tokenization
train_encodings = tokenizer(list(train_texts),truncation=True, padding = True)
test_encodings = tokenizer(list(test_texts),truncation=True, padding = True)
import torch
class IMDbDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
train_dataset = IMDbDataset(train_encodings, list(train_labels))
test_dataset = IMDbDataset(test_encodings, list(test_labels))
import evaluate
model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
metric = evaluate.load("accuracy")
training_args = TrainingArguments(
output_dir='./results', # output directory
num_train_epochs=1, # total number of training epochs
per_device_train_batch_size=16, # batch size per device during training
per_device_eval_batch_size=64, # batch size for evaluation
warmup_steps=0, # number of warmup steps for learning rate scheduler
weight_decay=0 # strength of weight decay
)
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
compute_metrics=compute_metrics,
)
trainer.train()
model = model.to(device="cpu")
our_predicts = pipeline(model = model, tokenizer=tokenizer, task="text-classification")
print(our_predicts("This is a pretty solid product. It lasted a while and I enjoyed using it. 10/10 would recommend."))
torch.save(our_predicts.model.state_dict(), "model.pt")