-
Notifications
You must be signed in to change notification settings - Fork 0
/
polarity_classification_training.py
135 lines (109 loc) · 5.1 KB
/
polarity_classification_training.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import code
from os.path import join
import evaluate
import numpy as np
import pandas as pd
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
DataCollatorWithPadding, Trainer, TrainingArguments)
import datasets
def read_data(folder, files):
li = []
for filename in files:
print(f'=== Reading {filename}')
df = pd.read_csv(join(folder, filename), index_col=None, header=0)
li.append(df)
df = pd.concat(li, axis=0, ignore_index=True)
return df
def preprocess_function(data):
return tokenizer(
data["text"],
truncation=True,
padding=True,
add_special_tokens=True)
def compute_metrics(eval_pred):
predictions, labels = eval_pred
predictions = np.argmax(predictions, axis=1)
accuracy = evaluate.load("accuracy").compute(predictions=predictions, references=labels)
precision = evaluate.load("precision").compute(predictions=predictions, references=labels, average='micro')
recall = evaluate.load("recall").compute(predictions=predictions, references=labels, average='micro')
f1 = evaluate.load("f1").compute(predictions=predictions, references=labels, average='micro')
return {**accuracy, **precision, **recall, **f1}
def manual_metrics(eval_pred):
predictions, labels = eval_pred
accuracy = evaluate.load("accuracy").compute(predictions=predictions, references=labels)
precision = evaluate.load("precision").compute(predictions=predictions, references=labels, average='micro')
recall = evaluate.load("recall").compute(predictions=predictions, references=labels, average='micro')
f1 = evaluate.load("f1").compute(predictions=predictions, references=labels, average='micro')
return {**accuracy, **precision, **recall, **f1}
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
if __name__ == "__main__":
POLUSA = {
'6k': {
'FOLDER': './data/polusa_balanced_6k',
'FILES': ['data.csv']
},
'90k': {
'FOLDER': './data/polusa_balanced_90k',
'FILES': ['data.csv']
},
'300k': {
'FOLDER': './data/polusa_300k',
'FILES': ['data.csv']
},
'432k': {
'FOLDER': './data/polusa_balanced_432k',
'FILES': ['data.csv']
},
'Full': {
'FOLDER': './data/polusa/polusa_balanced',
'FILES': ['2017_1.csv', '2017_2.csv', '2018_1.csv', '2018_2.csv', '2019_1.csv', '2019_2.csv']
}
}
POLUSA_VERSION = '300k' # <-- choose version here
FOLDER = POLUSA[POLUSA_VERSION]['FOLDER']
FILES = POLUSA[POLUSA_VERSION]['FILES']
df = read_data(FOLDER, FILES)
df = df.drop(df[df.label == 'UNDEFINED'].index)
df = df.drop(['id', 'date_publish', 'outlet', 'headline', 'lead', 'authors', 'domain', 'url'], axis=1)
df.label[df.label=='LEFT'] = 0
df.label[df.label=='CENTER'] = 1
df.label[df.label=='RIGHT'] = 2
print(f'LEFT articles: {len(df[df.label == 0])}\nCENTER articles: {len(df[df.label == 1])}\nRIGHT articles: {len(df[df.label == 2])}')
df_train, df_val, df_test = np.split(df.sample(frac=1, random_state=42), [int(.6 * len(df)), int(.8 * len(df))])
print(f'Train size: {len(df_train)}\nValidation size: {len(df_val)}\nTest size: {len(df_test)}')
ds_train_tokenized = datasets.Dataset.from_pandas(df_train).map(preprocess_function, batched=True)
ds_val_tokenized = datasets.Dataset.from_pandas(df_val).map(preprocess_function, batched=True)
ds_test_tokenized = datasets.Dataset.from_pandas(df_test).map(preprocess_function, batched=True)
trainning = True
openShell = True
if trainning:
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
id2label = {0: "LEFT", 1: "CENTER", 2: "RIGHT"}
label2id = {"LEFT": 0, "CENTER": 1, "RIGHT": 2}
# model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=3, id2label=id2label, label2id=label2id)
model = AutoModelForSequenceClassification.from_pretrained("sentence-transformers/paraphrase-MiniLM-L6-v2", num_labels=3, id2label=id2label, label2id=label2id)
# model = AutoModelForSequenceClassification.from_pretrained("./model/checkpoint-5138", num_labels=3, id2label=id2label, label2id=label2id)
training_args = TrainingArguments(
output_dir="model",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=1,
weight_decay=0.01,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
push_to_hub=False,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=ds_train_tokenized,
eval_dataset=ds_val_tokenized,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
trainer.train()
if openShell:
code.interact(local=locals())