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, classification_report from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments import torch import os # 1. Load Data df = pd.read_csv('mail_data.csv', names=['Category', 'Message'], header=None, skiprows=1) df['label'] = df['Category'].map({'ham': 0, 'spam': 1}) _, test_texts, _, test_labels = train_test_split( df['Message'].values.tolist(), df['label'].values.tolist(), test_size=0.2, random_state=42, stratify=df['label'].values ) # 2. Tokenization tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') 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) test_dataset = EmailDataset(test_encodings, test_labels) # 3. Load Model from Checkpoint # Find the checkpoint directory checkpoint_dir = [d for d in os.listdir('./results') if d.startswith('checkpoint')][0] model_path = os.path.join('./results', checkpoint_dir) print(f"Loading model from {model_path}") model = DistilBertForSequenceClassification.from_pretrained(model_path) # 4. Evaluation trainer = Trainer(model=model) predictions = trainer.predict(test_dataset) preds = predictions.predictions.argmax(-1) labels = predictions.label_ids report = classification_report(labels, preds, target_names=['ham', 'spam']) cm = confusion_matrix(labels, preds) acc = accuracy_score(labels, preds) print(f"Accuracy: {acc}") print(report) with open('results.txt', 'w') as f: f.write(f"Final Evaluation Results (from {checkpoint_dir}):\n") f.write(f"Accuracy: {acc}\n") f.write(f"\nClassification Report:\n{report}\n") f.write(f"\nConfusion Matrix:\n{cm}\n") print("Evaluation complete. Results saved to results.txt")