File size: 2,227 Bytes
bf1e802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ['WANDB_DISABLED'] = "true"
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from transformers import (
    AutoTokenizer, 
    DataCollatorWithPadding,
    TrainingArguments,
    Trainer,
    AutoModelForSequenceClassification
)
from datasets import Dataset
 
#######################################
########## FinBERT training ###########
#######################################

class args:
    model = 'ProsusAI/finbert'

df = pd.read_csv('all-data.csv', 
                 names = ['labels','messages'],
                 encoding='ISO-8859-1')

df = df[['messages', 'labels']]

le = LabelEncoder()
df['labels'] = le.fit_transform(df['labels'])

X, y = df['messages'].values, df['labels'].values

xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.1) 
xtrain, xvalid, ytrain, yvalid = train_test_split(xtrain, ytrain, test_size=0.2) 

train_dataset_raw = Dataset.from_dict({'text':xtrain, 'labels':ytrain})
valid_dataset_raw = Dataset.from_dict({'text':xvalid, 'labels':yvalid})

tokenizer = AutoTokenizer.from_pretrained(args.model)

def tokenize_fn(examples):
    return tokenizer(examples['text'], truncation=True)

train_dataset = train_dataset_raw.map(tokenize_fn, batched=True)
valid_dataset = valid_dataset_raw.map(tokenize_fn, batched=True)

data_collator = DataCollatorWithPadding(tokenizer)

model = AutoModelForSequenceClassification.from_pretrained(args.model)

train_args = TrainingArguments(
    './Finbert Trained/',
    per_device_train_batch_size=16,
    per_device_eval_batch_size=2*16,
    num_train_epochs=5,
    learning_rate=2e-5,
    weight_decay=0.01,
    warmup_ratio=0.1,    
    do_eval=True,
    do_train=True,
    do_predict=True,
    evaluation_strategy='epoch',
    save_strategy="no",
)

trainer = Trainer(
    model,
    train_args,
    train_dataset=train_dataset,
    eval_dataset=valid_dataset,
    data_collator=data_collator,
    tokenizer=tokenizer 
)

trainer.train()

# saving the model and the weights
model.save_pretrained('fine_tuned_FinBERT')
# saving the tokenizer
tokenizer.save_pretrained("fine_tuned_FinBERT/tokenizer/")