| import pandas as pd |
| import numpy as np |
| from sklearn.model_selection import train_test_split |
| from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix |
| from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments |
| import torch |
|
|
| |
| df = pd.read_csv('mail_data.csv', names=['Category', 'Message'], header=None, skiprows=1) |
| df['label'] = df['Category'].map({'ham': 0, 'spam': 1}) |
|
|
| train_texts, test_texts, train_labels, test_labels = train_test_split( |
| df['Message'].values.tolist(), df['label'].values.tolist(), test_size=0.2, random_state=42, stratify=df['label'].values |
| ) |
|
|
| |
| tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') |
|
|
| train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=128) |
| test_encodings = tokenizer(test_texts, truncation=True, padding=True, max_length=128) |
|
|
| class EmailDataset(torch.utils.data.Dataset): |
| def __init__(self, encodings, labels): |
| self.encodings = encodings |
| self.labels = labels |
|
|
| def __getitem__(self, idx): |
| item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} |
| item['labels'] = torch.tensor(self.labels[idx]) |
| return item |
|
|
| def __len__(self): |
| return len(self.labels) |
|
|
| train_dataset = EmailDataset(train_encodings, train_labels) |
| test_dataset = EmailDataset(test_encodings, test_labels) |
|
|
| |
| model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=2) |
|
|
| def compute_metrics(pred): |
| labels = pred.label_ids |
| preds = pred.predictions.argmax(-1) |
| precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary') |
| acc = accuracy_score(labels, preds) |
| return { |
| 'accuracy': acc, |
| 'f1': f1, |
| 'precision': precision, |
| 'recall': recall |
| } |
|
|
| |
| training_args = TrainingArguments( |
| output_dir='./results', |
| num_train_epochs=3, |
| per_device_train_batch_size=16, |
| per_device_eval_batch_size=64, |
| warmup_steps=500, |
| weight_decay=0.01, |
| logging_dir='./logs', |
| logging_steps=10, |
| eval_strategy="epoch", |
| save_strategy="epoch", |
| load_best_model_at_end=True, |
| ) |
|
|
| |
| trainer = Trainer( |
| model=model, |
| args=training_args, |
| train_dataset=train_dataset, |
| eval_dataset=test_dataset, |
| compute_metrics=compute_metrics, |
| ) |
|
|
| print("Starting training with HF Trainer...") |
| trainer.train() |
|
|
| |
| print("Evaluating...") |
| eval_results = trainer.evaluate() |
| print(eval_results) |
|
|
| |
| predictions = trainer.predict(test_dataset) |
| preds = predictions.predictions.argmax(-1) |
| labels = predictions.label_ids |
|
|
| from sklearn.metrics import classification_report |
| report = classification_report(labels, preds, target_names=['ham', 'spam']) |
| cm = confusion_matrix(labels, preds) |
|
|
| with open('results.txt', 'w') as f: |
| f.write(f"Final Evaluation Results:\n{eval_results}\n") |
| f.write(f"\nClassification Report:\n{report}\n") |
| f.write(f"\nConfusion Matrix:\n{cm}\n") |
|
|
| print("Training complete. Results saved to results.txt") |