File size: 3,952 Bytes
9047480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import pandas as pd
import os
from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments, AutoTokenizer, RobertaTokenizer, RobertaForSequenceClassification, GPT2Tokenizer, GPT2ForSequenceClassification
import torch
from torch.utils.data import Dataset
torch.cuda.empty_cache()

class MultiLabelClassifierDataset(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]).float()
        return item

    def __len__(self):
        return len(self.labels)


work_dir = os.path.dirname(os.path.realpath(__file__)) + '/'
dataset_dir = work_dir + 'jigsaw-toxic-comment-classification-challenge/'

classifiers = ['toxic', 'severe_toxic', 'obscene',
               'threat', 'insult', 'identity_hate']

df = pd.read_csv(dataset_dir + 'train.csv')
df = df.sample(frac=1).reset_index(drop=True)  # Shuffle

train_df = df[:int(len(df)*0.1)]

train_labels = train_df[classifiers].to_numpy()

device = torch.device('cuda')
print("Using device: ", device)


training_args = TrainingArguments(
    output_dir='./results',
    num_train_epochs=2,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=64,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir='./logs',
    logging_steps=10,
    fp16=True
)

print("BERT")
bert_dir = work_dir + 'bert/'

print("Model base: ", "vinai/bertweet-base")
tokenizer = AutoTokenizer.from_pretrained(
    "vinai/bertweet-base", model_max_length=128)

train_encodings = tokenizer(
    train_df['comment_text'].tolist(), truncation=True, padding=True)

print("Training model to be stored in" + bert_dir)

print("Creating dataset")
train_dataset = MultiLabelClassifierDataset(train_encodings, train_labels)

print("Loading model for training...")
model = AutoModelForSequenceClassification.from_pretrained(
    'vinai/bertweet-base', num_labels=6)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset
)

trainer.train()

trainer.save_model(bert_dir + '_bert_model')


training_args = TrainingArguments(
    output_dir='./results',
    num_train_epochs=1,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=16,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir='./logs',
    logging_steps=10,
    fp16=True
)

print("RoBERTa")
roberta_dir = work_dir + 'roberta/'

tokenizer = RobertaTokenizer.from_pretrained(
    'roberta-base', model_max_length=128)

train_encodings = tokenizer(
    train_df['comment_text'].tolist(), truncation=True, padding=True)


train_dataset = MultiLabelClassifierDataset(train_encodings, train_labels)

model = AutoModelForSequenceClassification.from_pretrained(
    'roberta-base', num_labels=6)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset
)

trainer.train()

trainer.save_model(roberta_dir + '_roberta_model')


training_args = TrainingArguments(
    output_dir='./results',
    num_train_epochs=1,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=64,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir='./logs',
    logging_steps=10,
    fp16=True
)


print("DISTILBERT")
distilbert_dir = work_dir + 'distilbert/'

tokenizer = AutoTokenizer.from_pretrained(
    'distilbert-base-cased', model_max_length=128)

train_encodings = tokenizer(
    train_df['comment_text'].tolist(), truncation=True, padding=True)


train_dataset = MultiLabelClassifierDataset(train_encodings, train_labels)

model = AutoModelForSequenceClassification.from_pretrained(
    'distilbert-base-cased', num_labels=6)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset
)

trainer.train()

trainer.save_model(distilbert_dir + '_distilbert_model')