class created
Browse files- .gitignore +2 -0
- explainableai.py +58 -0
- finetune-emotions.py +42 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
.DS_Store
|
explainableai.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, Trainer, TrainingArguments
|
2 |
+
from sklearn.metrics import accuracy_score, f1_score
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
CITDA_EPOCHS = 10
|
7 |
+
CITDA_WEIGHT_DECAY = 0.05 # L2 regularization
|
8 |
+
CITDA_BATCH_SIZE = 32
|
9 |
+
CITDA_LEARNINGRATE= 2e-5
|
10 |
+
|
11 |
+
class CITDA:
|
12 |
+
def __init__(self, model, labels, base_model_name, tokenizer, encoded_data):
|
13 |
+
self.labels = labels
|
14 |
+
# self.device = device
|
15 |
+
self.tokenizer = tokenizer
|
16 |
+
self.model = model
|
17 |
+
self.encoded_data = encoded_data
|
18 |
+
|
19 |
+
def _get_trainer(self):
|
20 |
+
def compute_metrics(pred):
|
21 |
+
labels = pred.label_ids
|
22 |
+
preds = pred.predictions.argmax(-1)
|
23 |
+
f1 = f1_score(labels, preds, average="weighted")
|
24 |
+
acc = accuracy_score(labels, preds)
|
25 |
+
return {"accuracy": acc, "f1": f1}
|
26 |
+
|
27 |
+
training_args = TrainingArguments(output_dir="results",
|
28 |
+
num_train_epochs=CITDA_EPOCHS,
|
29 |
+
learning_rate=CITDA_LEARNINGRATE,
|
30 |
+
per_device_train_batch_size=CITDA_BATCH_SIZE,
|
31 |
+
per_device_eval_batch_size=CITDA_BATCH_SIZE,
|
32 |
+
load_best_model_at_end=True,
|
33 |
+
metric_for_best_model="f1",
|
34 |
+
weight_decay=CITDA_WEIGHT_DECAY,
|
35 |
+
evaluation_strategy="epoch",
|
36 |
+
save_strategy="epoch",
|
37 |
+
disable_tqdm=False)
|
38 |
+
trainer = Trainer(model=self.model, tokenizer=self.tokenizer, args=training_args,
|
39 |
+
compute_metrics=compute_metrics,
|
40 |
+
train_dataset = self.encoded_data["train"],
|
41 |
+
eval_dataset = self.encoded_data["validation"],
|
42 |
+
report_to="wandb")
|
43 |
+
return trainer
|
44 |
+
|
45 |
+
def train(self):
|
46 |
+
trainer = self._get_trainer()
|
47 |
+
results = trainer.evaluate()
|
48 |
+
preds_output = trainer.predict(encoded_data["validation"])
|
49 |
+
|
50 |
+
y_valid = np.array(encoded_data["validation"]["label"])
|
51 |
+
y_preds = np.argmax(preds_output.predictions, axis=1)
|
52 |
+
|
53 |
+
#Saving the fine-tuned model
|
54 |
+
self.model.save_pretrained('./model')
|
55 |
+
self.tokenizer.save_pretrained('./model')
|
56 |
+
|
57 |
+
return y_valid, y_pred
|
58 |
+
|
finetune-emotions.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Modified https://github.com/bhadreshpsavani/ExploringSentimentalAnalysis/blob/main/SentimentalAnalysisWithDistilbert.ipynb
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from sklearn.metrics import confusion_matrix
|
5 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
6 |
+
from datasets import load_dataset
|
7 |
+
#import matplotlib.pyplot as plt
|
8 |
+
import seaborn as sns
|
9 |
+
import explainableai
|
10 |
+
|
11 |
+
BASE_MODEL_NAME = "bert-base-uncased"
|
12 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
13 |
+
|
14 |
+
|
15 |
+
def save_confusion_matrix(y_valid, y_preds):
|
16 |
+
cm = confusion_matrix(y_valid, y_preds)
|
17 |
+
f = sns.heatmap(cm, annot=True, fmt='d')
|
18 |
+
f.figure.savefig("confusion_matrix.png")
|
19 |
+
|
20 |
+
def get_encoded_data(tokenizer):
|
21 |
+
def tokenize(batch):
|
22 |
+
return tokenizer(batch["text"], padding=True, truncation=True)
|
23 |
+
emotions = load_dataset("emotion")
|
24 |
+
emotions_encoded = emotions.map(tokenize, batched=True, batch_size=None)
|
25 |
+
emotions_encoded.set_format("torch", columns=["input_ids", "attention_mask", "label"])
|
26 |
+
return emotions_encoded
|
27 |
+
if __name__ == "__main__":
|
28 |
+
labels = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
29 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
30 |
+
pretrained_model_name_or_path = BASE_MODEL_NAME,
|
31 |
+
num_labels = len(labels),
|
32 |
+
id2label=[{i: labels[i]} for i in range(len(labels))],
|
33 |
+
resume_download=True,).to(device)
|
34 |
+
|
35 |
+
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)
|
36 |
+
|
37 |
+
encoded_data = get_encoded_data(tokenizer)
|
38 |
+
citda = explainableai.CITDA(model, labels, BASE_MODEL_NAME, tokenizer, encoded_data)
|
39 |
+
y_valid, y_pred = citda.train()
|
40 |
+
|
41 |
+
save_confusion_matrix(y_valid, y_preds)
|
42 |
+
print("y_valid=",len(y_valid), "y_pred=", len(y_pred))
|