Add model training script
Browse files- train_abuse_model.py +212 -0
train_abuse_model.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# # Install core packages
|
2 |
+
# !pip install -U transformers datasets accelerate
|
3 |
+
|
4 |
+
# Python standard + ML packages
|
5 |
+
import pandas as pd
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
|
9 |
+
from sklearn.model_selection import train_test_split
|
10 |
+
from sklearn.metrics import classification_report, precision_recall_fscore_support
|
11 |
+
|
12 |
+
from torch.utils.data import Dataset
|
13 |
+
|
14 |
+
# Hugging Face transformers
|
15 |
+
from transformers import (
|
16 |
+
AutoTokenizer,
|
17 |
+
BertTokenizer,
|
18 |
+
BertForSequenceClassification,
|
19 |
+
AutoModelForSequenceClassification,
|
20 |
+
Trainer,
|
21 |
+
TrainingArguments
|
22 |
+
)
|
23 |
+
|
24 |
+
# Custom Dataset class
|
25 |
+
class AbuseDataset(Dataset):
|
26 |
+
def __init__(self, texts, labels):
|
27 |
+
self.encodings = tokenizer(texts, truncation=True, padding=True, max_length=512)
|
28 |
+
self.labels = labels
|
29 |
+
|
30 |
+
def __len__(self):
|
31 |
+
return len(self.labels)
|
32 |
+
|
33 |
+
def __getitem__(self, idx):
|
34 |
+
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
|
35 |
+
item["labels"] = torch.tensor(self.labels[idx], dtype=torch.float)
|
36 |
+
return item
|
37 |
+
|
38 |
+
|
39 |
+
# Convert label values to soft scores: "yes" = 1.0, "plausibly" = 0.5, others = 0.0
|
40 |
+
def label_row_soft(row):
|
41 |
+
labels = []
|
42 |
+
for col in label_columns:
|
43 |
+
val = str(row[col]).strip().lower()
|
44 |
+
if val == "yes":
|
45 |
+
labels.append(1.0)
|
46 |
+
elif val == "plausibly":
|
47 |
+
labels.append(0.5)
|
48 |
+
else:
|
49 |
+
labels.append(0.0)
|
50 |
+
return labels
|
51 |
+
|
52 |
+
# Function to map probabilities to 3 classes
|
53 |
+
# (0.0, 0.5, 1.0) based on thresholds
|
54 |
+
def map_to_3_classes(prob_array, low, high):
|
55 |
+
"""Map probabilities to 0.0, 0.5, 1.0 using thresholds."""
|
56 |
+
mapped = np.zeros_like(prob_array)
|
57 |
+
mapped[(prob_array > low) & (prob_array <= high)] = 0.5
|
58 |
+
mapped[prob_array > high] = 1.0
|
59 |
+
return mapped
|
60 |
+
|
61 |
+
def convert_to_label_strings(array):
|
62 |
+
"""Convert float label array to list of strings."""
|
63 |
+
return [label_map[val] for val in array.flatten()]
|
64 |
+
|
65 |
+
def tune_thresholds(probs, true_labels, verbose=True):
|
66 |
+
"""Search for best (low, high) thresholds by macro F1 score."""
|
67 |
+
best_macro_f1 = 0.0
|
68 |
+
best_low, best_high = 0.0, 0.0
|
69 |
+
|
70 |
+
for low in np.arange(0.2, 0.5, 0.05):
|
71 |
+
for high in np.arange(0.55, 0.8, 0.05):
|
72 |
+
if high <= low:
|
73 |
+
continue
|
74 |
+
|
75 |
+
pred_soft = map_to_3_classes(probs, low, high)
|
76 |
+
pred_str = convert_to_label_strings(pred_soft)
|
77 |
+
true_str = convert_to_label_strings(true_labels)
|
78 |
+
|
79 |
+
_, _, f1, _ = precision_recall_fscore_support(
|
80 |
+
true_str, pred_str,
|
81 |
+
labels=["no", "plausibly", "yes"],
|
82 |
+
average="macro",
|
83 |
+
zero_division=0
|
84 |
+
)
|
85 |
+
if verbose:
|
86 |
+
print(f"low={low:.2f}, high={high:.2f} -> macro F1={f1:.3f}")
|
87 |
+
if f1 > best_macro_f1:
|
88 |
+
best_macro_f1 = f1
|
89 |
+
best_low, best_high = low, high
|
90 |
+
|
91 |
+
return best_low, best_high, best_macro_f1
|
92 |
+
|
93 |
+
def evaluate_model_with_thresholds(trainer, test_dataset):
|
94 |
+
"""Run full evaluation with automatic threshold tuning."""
|
95 |
+
print("\nπ Running model predictions...")
|
96 |
+
predictions = trainer.predict(test_dataset)
|
97 |
+
probs = torch.sigmoid(torch.tensor(predictions.predictions)).numpy()
|
98 |
+
true_soft = np.array(predictions.label_ids)
|
99 |
+
|
100 |
+
print("\nπ Tuning thresholds...")
|
101 |
+
best_low, best_high, best_f1 = tune_thresholds(probs, true_soft)
|
102 |
+
|
103 |
+
print(f"\nβ
Best thresholds: low={best_low:.2f}, high={best_high:.2f} (macro F1={best_f1:.3f})")
|
104 |
+
|
105 |
+
final_pred_soft = map_to_3_classes(probs, best_low, best_high)
|
106 |
+
final_pred_str = convert_to_label_strings(final_pred_soft)
|
107 |
+
true_str = convert_to_label_strings(true_soft)
|
108 |
+
|
109 |
+
print("\nπ Final Evaluation Report (multi-class per label):\n")
|
110 |
+
print(classification_report(
|
111 |
+
true_str,
|
112 |
+
final_pred_str,
|
113 |
+
labels=["no", "plausibly", "yes"],
|
114 |
+
zero_division=0
|
115 |
+
))
|
116 |
+
|
117 |
+
return {
|
118 |
+
"thresholds": (best_low, best_high),
|
119 |
+
"macro_f1": best_f1,
|
120 |
+
"true_labels": true_str,
|
121 |
+
"pred_labels": final_pred_str
|
122 |
+
}
|
123 |
+
|
124 |
+
# Load dataset
|
125 |
+
df = pd.read_excel("Abusive Relationship Stories - Technion & MSF.xlsx")
|
126 |
+
|
127 |
+
# Define text and label columns
|
128 |
+
text_column = "post_body"
|
129 |
+
label_columns = [
|
130 |
+
'emotional_violence', 'physical_violence', 'sexual_violence', 'spiritual_violence',
|
131 |
+
'economic_violence', 'past_offenses', 'social_isolation', 'refuses_treatment',
|
132 |
+
'suicidal_threats', 'mental_condition', 'daily_activity_control', 'violent_behavior',
|
133 |
+
'unemployment', 'substance_use', 'obsessiveness', 'jealousy', 'outbursts',
|
134 |
+
'ptsd', 'hard_childhood', 'emotional_dependency', 'prevention_of_care',
|
135 |
+
'fear_based_relationship', 'humiliation', 'physical_threats',
|
136 |
+
'presence_of_others_in_assault', 'signs_of_injury', 'property_damage',
|
137 |
+
'access_to_weapons', 'gaslighting'
|
138 |
+
]
|
139 |
+
|
140 |
+
print(np.shape(df))
|
141 |
+
# Clean data
|
142 |
+
df = df[[text_column] + label_columns]
|
143 |
+
print(np.shape(df))
|
144 |
+
df = df.dropna(subset=[text_column])
|
145 |
+
print(np.shape(df))
|
146 |
+
|
147 |
+
df["label_vector"] = df.apply(label_row_soft, axis=1)
|
148 |
+
label_matrix = df["label_vector"].tolist()
|
149 |
+
|
150 |
+
|
151 |
+
#model_name = "onlplab/alephbert-base"
|
152 |
+
model_name = "microsoft/deberta-v3-base"
|
153 |
+
|
154 |
+
# Load pretrained Hebrew model (AlephBERT) for fine-tuning
|
155 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
156 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
157 |
+
model_name,
|
158 |
+
num_labels=len(label_columns),
|
159 |
+
problem_type="multi_label_classification"
|
160 |
+
)
|
161 |
+
|
162 |
+
# # Optional: Freeze base model layers (only train classifier head)
|
163 |
+
# freeze_base = False
|
164 |
+
# if freeze_base:
|
165 |
+
# for name, param in model.bert.named_parameters():
|
166 |
+
# param.requires_grad = False
|
167 |
+
|
168 |
+
# Freeze bottom 6 layers of DeBERTa encoder
|
169 |
+
for name, param in model.named_parameters():
|
170 |
+
if any(f"encoder.layer.{i}." in name for i in range(0, 6)):
|
171 |
+
param.requires_grad = False
|
172 |
+
|
173 |
+
|
174 |
+
# Proper 3-way split: train / val / test
|
175 |
+
train_val_texts, test_texts, train_val_labels, test_labels = train_test_split(
|
176 |
+
df[text_column].tolist(), label_matrix, test_size=0.2, random_state=42
|
177 |
+
)
|
178 |
+
|
179 |
+
train_texts, val_texts, train_labels, val_labels = train_test_split(
|
180 |
+
train_val_texts, train_val_labels, test_size=0.1, random_state=42
|
181 |
+
)
|
182 |
+
|
183 |
+
train_dataset = AbuseDataset(train_texts, train_labels)
|
184 |
+
val_dataset = AbuseDataset(val_texts, val_labels)
|
185 |
+
test_dataset = AbuseDataset(test_texts, test_labels)
|
186 |
+
|
187 |
+
|
188 |
+
# TrainingArguments for HuggingFace Trainer (logging, saving)
|
189 |
+
training_args = TrainingArguments(
|
190 |
+
output_dir="./results",
|
191 |
+
num_train_epochs=3,
|
192 |
+
per_device_train_batch_size=8,
|
193 |
+
per_device_eval_batch_size=8,
|
194 |
+
evaluation_strategy="epoch",
|
195 |
+
save_strategy="epoch",
|
196 |
+
logging_dir="./logs",
|
197 |
+
logging_steps=10,
|
198 |
+
)
|
199 |
+
|
200 |
+
# Train using HuggingFace Trainer
|
201 |
+
trainer = Trainer(
|
202 |
+
model=model,
|
203 |
+
args=training_args,
|
204 |
+
train_dataset=train_dataset,
|
205 |
+
eval_dataset=val_dataset
|
206 |
+
)
|
207 |
+
|
208 |
+
# Start training!
|
209 |
+
trainer.train()
|
210 |
+
|
211 |
+
label_map = {0.0: "no", 0.5: "plausibly", 1.0: "yes"}
|
212 |
+
evaluate_model_with_thresholds(trainer, test_dataset)
|