-
Notifications
You must be signed in to change notification settings - Fork 0
/
exp2_Aspects_fewshot_classification_roberta_large.py
180 lines (144 loc) · 6.66 KB
/
exp2_Aspects_fewshot_classification_roberta_large.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import logging
import os
import pandas as pd
import sklearn
from simpletransformers.classification import ClassificationModel
from sklearn.utils import class_weight
logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)
def get_train_args(model_dir, exp_i=1):
train_args = {
"output_dir": model_dir,
"cache_dir": "cache/",
"best_model_dir": model_dir + "/best_model/",
"fp16": False,
"fp16_opt_level": "O1",
"gradient_accumulation_steps": 1,
"weight_decay": 0.2,
"adam_epsilon": 1e-9,
"warmup_ratio": 0.1,
"warmup_steps": 0,
"max_grad_norm": 1.0,
# "scheduler": "cosine_with_hard_restarts_schedule_with_warmup",
"n_gpu": 1,
"learning_rate": 5e-6,
"num_train_epochs": 20,
"max_seq_length": 256,
"train_batch_size": 4,
"eval_batch_size": 8,
"do_lower_case": False,
"strip_accents": True,
"logging_steps": 50,
"evaluate_during_training": True,
"evaluate_during_training_steps": 0,
"evaluate_during_training_verbose": True,
"use_cached_eval_features": False,
"save_eval_checkpoints": False,
"save_steps": 0,
"no_cache": True,
"save_model_every_epoch": False,
"tensorboard_dir": None,
"overwrite_output_dir": True,
"reprocess_input_data": True,
"silent": False,
"use_multiprocessing": True,
"wandb_project": None,
"wandb_kwargs": {},
"use_early_stopping": False,
"early_stopping_patience": 4,
"early_stopping_delta": 0,
"early_stopping_metric": "f1",
"early_stopping_metric_minimize": False,
"manual_seed": 9721 * exp_i,
"encoding": None,
"config": {},
}
return train_args
def precision_macro(y_true, y_pred):
return sklearn.metrics.precision_score(y_true, y_pred, average='macro')
def recall_macro(y_true, y_pred):
return sklearn.metrics.recall_score(y_true, y_pred, average='macro')
def f1_macro(y_true, y_pred):
return sklearn.metrics.f1_score(y_true, y_pred, average='macro')
if __name__ == '__main__':
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# split a dev set from the training data
train_df = pd.read_csv("Train-splits/testnway/full_shot/NuclearEnergy_train.csv", header=None,
names=['text', 'labels'])
test_df = pd.read_csv("Train-splits/testnway/full_shot/NuclearEnergy_test.csv", header=None,
names=['text', 'labels'])
dev_df = pd.read_csv("Train-splits/testnway/full_shot/NuclearEnergy_dev.csv", header=None,
names=['text', 'labels'])
# weights
all_train_labels = train_df.labels.tolist()
unique_labels = list(set(all_train_labels))
unique_labels.sort()
label2int = {label: i for i, label in enumerate(unique_labels)}
int2label = {i: label for i, label in enumerate(unique_labels)}
class_weights = class_weight.compute_class_weight(class_weight='balanced', classes=unique_labels, y=all_train_labels)
cw_dict = {label2int[l]: class_weights[i] for i, l in enumerate(unique_labels)}
print(cw_dict)
print(int2label)
#exit(0)
train_df.labels = [label2int[label] for label in train_df.labels]
test_df.labels = [label2int[label] for label in test_df.labels]
dev_df.labels = [label2int[label] for label in dev_df.labels]
# start
models_to_test = [
("roberta", "roberta-large")
]
model_repititions: int = 5
k_train_splits = [100]
# few-shots with k random samples per class
for k in k_train_splits:
print(f"{k} Few-Shots")
if k ==0:
train_split_df = pd.DataFrame(columns=['text','labels'])
else:
train_split_df = pd.read_csv(f'Train-splits/testnway/{k}_shot/NuclearEnergy_train.csv',
header=None,names=['text', 'labels'])
train_split_df.labels = [label2int[label] for label in train_split_df.labels]
# r repititions
for r in range(1, 6):
use_cuda = True
model_base = f"models_seed/exp2_{k}shot_trial{r}/"
for model_i, model_to_test in enumerate(models_to_test):
print(model_to_test, "\n", "*********************************************")
model_name = model_to_test[1].replace("/", "_")
model_dir = model_base + model_name
train_args = get_train_args(model_dir, r)
if model_i >= 0:
# Create a ClassificationModel
model = ClassificationModel(
model_to_test[0],
model_to_test[1],
num_labels=len(unique_labels),
# weight=cw_dict,
use_cuda=use_cuda,
cuda_device=-1,
args=train_args
)
if k > 0:
model.train_model(train_split_df, train_args['best_model_dir'],eval_df=dev_df, precision=precision_macro, recall=recall_macro,
f1=f1_macro)
if k > 0:
model = ClassificationModel(model_to_test[0], train_args['best_model_dir'], use_cuda=use_cuda,
cuda_device=0, args=train_args)
result, model_outputs, wrong_predictions = model.eval_model(test_df, acc=sklearn.metrics.accuracy_score,
precision=precision_macro,
recall=recall_macro, f1=f1_macro)
# get labels
pred_labels = model_outputs.argmax(axis=-1).tolist()
true_labels = test_df["labels"].tolist()
# report
report = sklearn.metrics.classification_report(true_labels, pred_labels, digits=3)
kappa = sklearn.metrics.cohen_kappa_score(true_labels, pred_labels)
print(report)
print(kappa)
with open(model_dir + "/results.txt", "w") as f:
f.write(report)
f.write("\nKappa: " + str(kappa))
# pred output
test_df['predicted'] = pred_labels
test_df.to_csv(model_dir + "/fame_argaspects.csv")