updated training script
Browse files- finance/train_finbert.py +37 -52
finance/train_finbert.py
CHANGED
|
@@ -11,85 +11,79 @@ from transformers import (
|
|
| 11 |
AutoTokenizer,
|
| 12 |
AutoModelForSequenceClassification,
|
| 13 |
Trainer,
|
| 14 |
-
TrainingArguments
|
| 15 |
)
|
| 16 |
from datasets import Dataset
|
| 17 |
import numpy as np
|
| 18 |
from sklearn.metrics import accuracy_score, f1_score
|
| 19 |
import os
|
| 20 |
|
| 21 |
-
|
| 22 |
def compute_metrics(p):
|
| 23 |
"""Computes and returns evaluation metrics."""
|
| 24 |
preds = np.argmax(p.predictions, axis=1)
|
| 25 |
-
f1 = f1_score(p.label_ids, preds, average=
|
| 26 |
acc = accuracy_score(p.label_ids, preds)
|
| 27 |
return {"accuracy": acc, "f1": f1}
|
| 28 |
|
| 29 |
-
|
| 30 |
def main():
|
| 31 |
"""Main function to load data, fine-tune the FinBERT model, and save it."""
|
| 32 |
-
# 1.
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
try:
|
| 35 |
-
# Build the correct path to the data file
|
| 36 |
-
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 37 |
-
project_root = os.path.dirname(script_dir)
|
| 38 |
-
data_path = os.path.join(project_root, "Data", "emotion_dataset.csv")
|
| 39 |
df = pd.read_csv(data_path)
|
| 40 |
except FileNotFoundError:
|
| 41 |
-
print(
|
|
|
|
| 42 |
return
|
| 43 |
|
| 44 |
-
|
| 45 |
-
df
|
| 46 |
-
|
|
|
|
| 47 |
label_encoder = LabelEncoder()
|
| 48 |
-
df[
|
| 49 |
num_labels = len(label_encoder.classes_)
|
| 50 |
-
|
| 51 |
id2label = {i: label for i, label in enumerate(label_encoder.classes_)}
|
| 52 |
label2id = {label: i for i, label in enumerate(label_encoder.classes_)}
|
|
|
|
| 53 |
print(f"Found {num_labels} unique emotions.")
|
| 54 |
-
|
| 55 |
-
train_df, val_df = train_test_split(
|
| 56 |
-
df, test_size=0.2, random_state=42, stratify=df["labels"]
|
| 57 |
-
)
|
| 58 |
train_dataset = Dataset.from_pandas(train_df)
|
| 59 |
val_dataset = Dataset.from_pandas(val_df)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
print("Loading tokenizer and
|
| 63 |
model_name = "ProsusAI/finbert"
|
| 64 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 65 |
-
|
| 66 |
-
def tokenize_function(examples):
|
| 67 |
-
return tokenizer(
|
| 68 |
-
examples["text"], padding="max_length", truncation=True, max_length=128
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
tokenized_train_dataset = train_dataset.map(tokenize_function, batched=True)
|
| 72 |
-
tokenized_val_dataset = val_dataset.map(tokenize_function, batched=True)
|
| 73 |
-
|
| 74 |
-
# 3. Load and Configure the Model
|
| 75 |
-
print("Loading pre-trained model...")
|
| 76 |
model = AutoModelForSequenceClassification.from_pretrained(
|
| 77 |
model_name,
|
| 78 |
num_labels=num_labels,
|
| 79 |
id2label=id2label,
|
| 80 |
label2id=label2id,
|
| 81 |
-
ignore_mismatched_sizes=True
|
| 82 |
)
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
| 85 |
print("Starting model fine-tuning...")
|
| 86 |
-
output_dir = os.path.join(script_dir, "finbert_emotion_model")
|
| 87 |
print(f"Model will be saved to: {output_dir}")
|
| 88 |
|
| 89 |
training_args = TrainingArguments(
|
| 90 |
output_dir=output_dir,
|
| 91 |
num_train_epochs=1,
|
| 92 |
-
per_device_train_batch_size=16,
|
| 93 |
per_device_eval_batch_size=16,
|
| 94 |
logging_steps=100,
|
| 95 |
evaluation_strategy="epoch",
|
|
@@ -107,23 +101,14 @@ def main():
|
|
| 107 |
|
| 108 |
trainer.train()
|
| 109 |
|
| 110 |
-
# 5. Save
|
| 111 |
-
print(f"Training complete. Saving model
|
| 112 |
trainer.save_model(output_dir)
|
| 113 |
tokenizer.save_pretrained(output_dir)
|
| 114 |
-
print("
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
saved_files = os.listdir(output_dir)
|
| 119 |
-
print("\n--- VERIFICATION ---")
|
| 120 |
-
print(f"Successfully found the following files in '{output_dir}':")
|
| 121 |
-
for file_name in saved_files:
|
| 122 |
-
print(f"- {file_name}")
|
| 123 |
-
print("--------------------")
|
| 124 |
-
except Exception as e:
|
| 125 |
-
print(f"Could not verify saved files. Error: {e}")
|
| 126 |
-
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
| 129 |
main()
|
|
|
|
| 11 |
AutoTokenizer,
|
| 12 |
AutoModelForSequenceClassification,
|
| 13 |
Trainer,
|
| 14 |
+
TrainingArguments
|
| 15 |
)
|
| 16 |
from datasets import Dataset
|
| 17 |
import numpy as np
|
| 18 |
from sklearn.metrics import accuracy_score, f1_score
|
| 19 |
import os
|
| 20 |
|
|
|
|
| 21 |
def compute_metrics(p):
|
| 22 |
"""Computes and returns evaluation metrics."""
|
| 23 |
preds = np.argmax(p.predictions, axis=1)
|
| 24 |
+
f1 = f1_score(p.label_ids, preds, average='weighted', zero_division=0)
|
| 25 |
acc = accuracy_score(p.label_ids, preds)
|
| 26 |
return {"accuracy": acc, "f1": f1}
|
| 27 |
|
|
|
|
| 28 |
def main():
|
| 29 |
"""Main function to load data, fine-tune the FinBERT model, and save it."""
|
| 30 |
+
# --- 1. Define Paths for Colab Environment ---
|
| 31 |
+
# This path points directly to the file inside your Google Drive
|
| 32 |
+
data_path = "/content/drive/MyDrive/Colab_Data/emotion_dataset.csv"
|
| 33 |
+
# This is where the final trained model will be saved in your Google Drive
|
| 34 |
+
output_dir = "/content/drive/MyDrive/Colab_Data/finbert_emotion_model"
|
| 35 |
+
|
| 36 |
+
# --- 2. Load and Prepare the Dataset ---
|
| 37 |
+
print(f"Loading dataset from: {data_path}")
|
| 38 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
df = pd.read_csv(data_path)
|
| 40 |
except FileNotFoundError:
|
| 41 |
+
print("ERROR: 'emotion_dataset.csv' not found in '/content/drive/MyDrive/Colab_Data/'.")
|
| 42 |
+
print("Please make sure you have uploaded the file to the correct Google Drive folder.")
|
| 43 |
return
|
| 44 |
|
| 45 |
+
print("Dataset loaded successfully. Preprocessing data...")
|
| 46 |
+
df['text'] = df['Clean_Text'].fillna(df['Text'])
|
| 47 |
+
df.dropna(subset=['text', 'Emotion'], inplace=True)
|
| 48 |
+
|
| 49 |
label_encoder = LabelEncoder()
|
| 50 |
+
df['labels'] = label_encoder.fit_transform(df['Emotion'])
|
| 51 |
num_labels = len(label_encoder.classes_)
|
|
|
|
| 52 |
id2label = {i: label for i, label in enumerate(label_encoder.classes_)}
|
| 53 |
label2id = {label: i for i, label in enumerate(label_encoder.classes_)}
|
| 54 |
+
|
| 55 |
print(f"Found {num_labels} unique emotions.")
|
| 56 |
+
train_df, val_df = train_test_split(df, test_size=0.2, random_state=42, stratify=df['labels'])
|
|
|
|
|
|
|
|
|
|
| 57 |
train_dataset = Dataset.from_pandas(train_df)
|
| 58 |
val_dataset = Dataset.from_pandas(val_df)
|
| 59 |
|
| 60 |
+
# --- 3. Load Tokenizer and Model ---
|
| 61 |
+
print("Loading FinBERT tokenizer and model...")
|
| 62 |
model_name = "ProsusAI/finbert"
|
| 63 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 64 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
model = AutoModelForSequenceClassification.from_pretrained(
|
| 66 |
model_name,
|
| 67 |
num_labels=num_labels,
|
| 68 |
id2label=id2label,
|
| 69 |
label2id=label2id,
|
| 70 |
+
ignore_mismatched_sizes=True # ESSENTIAL for transfer learning
|
| 71 |
)
|
| 72 |
+
|
| 73 |
+
def tokenize_function(examples):
|
| 74 |
+
return tokenizer(examples['text'], padding="max_length", truncation=True, max_length=128)
|
| 75 |
|
| 76 |
+
tokenized_train_dataset = train_dataset.map(tokenize_function, batched=True)
|
| 77 |
+
tokenized_val_dataset = val_dataset.map(tokenize_function, batched=True)
|
| 78 |
+
|
| 79 |
+
# --- 4. Fine-Tune the Model ---
|
| 80 |
print("Starting model fine-tuning...")
|
|
|
|
| 81 |
print(f"Model will be saved to: {output_dir}")
|
| 82 |
|
| 83 |
training_args = TrainingArguments(
|
| 84 |
output_dir=output_dir,
|
| 85 |
num_train_epochs=1,
|
| 86 |
+
per_device_train_batch_size=16, # Safe batch size for Colab GPU
|
| 87 |
per_device_eval_batch_size=16,
|
| 88 |
logging_steps=100,
|
| 89 |
evaluation_strategy="epoch",
|
|
|
|
| 101 |
|
| 102 |
trainer.train()
|
| 103 |
|
| 104 |
+
# --- 5. Save the Final Model ---
|
| 105 |
+
print(f"Training complete. Saving final model to '{output_dir}'...")
|
| 106 |
trainer.save_model(output_dir)
|
| 107 |
tokenizer.save_pretrained(output_dir)
|
| 108 |
+
print("-----" * 10)
|
| 109 |
+
print("SUCCESS: Model saved to your Google Drive in the 'Colab_Data' folder.")
|
| 110 |
+
print("You can now download the 'finbert_emotion_model' folder and place it in your project's 'finance/' directory.")
|
| 111 |
+
print("-----" * 10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
if __name__ == "__main__":
|
| 114 |
main()
|