File size: 2,297 Bytes
ca1226e | 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 | 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")
|