Views
No views yet
prithivMLmods/Spam-Text-Detect-Analysis dataset and leverages Weights & Biases (wandb) for comprehensive experiment tracking.| File Name | Size | Description | Upload Status |
|---|---|---|---|
.gitattributes | 1.52 kB | Tracks files stored with Git LFS. | Uploaded |
README.md | 8.78 kB | Comprehensive documentation for the repository. | Updated |
config.json | 727 Bytes | Configuration file related to the model settings. | Uploaded |
model.safetensors | 438 MB | Model weights stored in safetensors format. | Uploaded (LFS) |
special_tokens_map.json | 125 Bytes | Mapping of special tokens for tokenizer handling. | Uploaded |
tokenizer_config.json | 1.24 kB | Tokenizer settings for initialization. | Uploaded |
vocab.txt | 232 kB | Vocabulary file for tokenizer use. | Uploaded |
bert-base-uncasedbert-base-uncased as the pre-trained backbone and is fine-tuned for the sequence classification task.1git clone <repository-url>
2cd <project-directory>pip install -r requirements.txtpip install transformers datasets wandb scikit-learntrain.py, run:1# Import necessary libraries
2from datasets import load_dataset, ClassLabel
3from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
4import torch
5from sklearn.metrics import accuracy_score, precision_recall_fscore_support
6
7# Load dataset
8dataset = load_dataset("prithivMLmods/Spam-Text-Detect-Analysis", split="train")
9
10# Encode labels as integers
11label_mapping = {"ham": 0, "spam": 1}
12dataset = dataset.map(lambda x: {"label": label_mapping[x["Category"]]})
13dataset = dataset.rename_column("Message", "text").remove_columns(["Category"])
14
15# Convert label column to ClassLabel for stratification
16class_label = ClassLabel(names=["ham", "spam"])
17dataset = dataset.cast_column("label", class_label)
18
19# Split into train and test
20dataset = dataset.train_test_split(test_size=0.2, stratify_by_column="label")
21train_dataset = dataset["train"]
22test_dataset = dataset["test"]
23
24# Load BERT tokenizer
25tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
26
27# Tokenize the data
28def tokenize_function(examples):
29 return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=128)
30
31train_dataset = train_dataset.map(tokenize_function, batched=True)
32test_dataset = test_dataset.map(tokenize_function, batched=True)
33
34# Set format for PyTorch
35train_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "label"])
36test_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "label"])
37
38# Load pre-trained BERT model
39model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
40
41# Move model to GPU if available
42device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
43model.to(device)
44
45# Define evaluation metric
46def compute_metrics(eval_pred):
47 predictions, labels = eval_pred
48 predictions = torch.argmax(torch.tensor(predictions), dim=-1)
49 precision, recall, f1, _ = precision_recall_fscore_support(labels, predictions, average="binary")
50 acc = accuracy_score(labels, predictions)
51 return {"accuracy": acc, "precision": precision, "recall": recall, "f1": f1}
52
53# Training arguments
54training_args = TrainingArguments(
55 output_dir="./results",
56 evaluation_strategy="epoch", # Evaluate after every epoch
57 save_strategy="epoch", # Save checkpoint after every epoch
58 learning_rate=2e-5,
59 per_device_train_batch_size=16,
60 per_device_eval_batch_size=16,
61 num_train_epochs=3,
62 weight_decay=0.01,
63 logging_dir="./logs",
64 logging_steps=10,
65 load_best_model_at_end=True,
66 metric_for_best_model="accuracy",
67 greater_is_better=True
68)
69
70# Trainer
71trainer = Trainer(
72 model=model,
73 args=training_args,
74 train_dataset=train_dataset,
75 eval_dataset=test_dataset,
76 compute_metrics=compute_metrics
77)
78
79# Train the model
80trainer.train()
81
82# Evaluate the model
83results = trainer.evaluate()
84print("Evaluation Results:", results)
85
86# Save the trained model
87model.save_pretrained("./saved_model")
88tokenizer.save_pretrained("./saved_model")
89
90# Load the model for inference
91loaded_model = BertForSequenceClassification.from_pretrained("./saved_model").to(device)
92loaded_tokenizer = BertTokenizer.from_pretrained("./saved_model")
93
94# Test the model on a custom input
95def predict(text):
96 inputs = loaded_tokenizer(text, return_tensors="pt", padding="max_length", truncation=True, max_length=128)
97 inputs = {k: v.to(device) for k, v in inputs.items()} # Move inputs to the same device as model
98 outputs = loaded_model(**inputs)
99 prediction = torch.argmax(outputs.logits, dim=-1).item()
100 return "Spam" if prediction == 1 else "Ham"
101
102# Example test
103example_text = "Congratulations! You've won a $1000 Walmart gift card. Click here to claim now."
104print("Prediction:", predict(example_text))1import wandb
2wandb.init(project="spam-detection")project-directory/
│
├── data/ # Dataset processing scripts
├── wandb/ # Logged artifacts from wandb runs
├── results/ # Save training and evaluation results
├── model/ # Trained model checkpoints
├── requirements.txt # List of dependencies
└── train.py # Main script for training the model1import gradio as gr
2import torch
3from transformers import BertTokenizer, BertForSequenceClassification
4
5# Load the pre-trained BERT model and tokenizer
6MODEL_PATH = "prithivMLmods/Spam-Bert-Uncased"
7tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
8model = BertForSequenceClassification.from_pretrained(MODEL_PATH)
9
10# Function to predict if a given text is Spam or Ham
11def predict_spam(text):
12 inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
13 with torch.no_grad():
14 outputs = model(**inputs)
15 logits = outputs.logits
16 prediction = torch.argmax(logits, axis=-1).item()
17 return "Spam" if prediction == 1 else "Ham"
18
19# Gradio UI
20inputs = gr.Textbox(label="Enter Text", placeholder="Type a message to check if it's Spam or Ham...")
21outputs = gr.Label(label="Prediction")
22
23examples = [
24 ["Win $1000 gift cards now by clicking here!"],
25 ["You have been selected for a lottery."],
26 ["Hello, how was your day?"],
27 ["Earn money without any effort. Click here."],
28 ["Meeting tomorrow at 10 AM. Don't be late."],
29 ["Claim your free prize now!"],
30 ["Are we still on for dinner tonight?"],
31 ["Exclusive offer just for you, act now!"],
32 ["Let's catch up over coffee soon."],
33 ["Congratulations, you've won a new car!"]
34]
35
36gr_interface = gr.Interface(
37 fn=predict_spam,
38 inputs=inputs,
39 outputs=outputs,
40 examples=examples,
41 title="Spam Detection with BERT",
42 description="Type a message in the text box to check if it's Spam or Ham using a pre-trained BERT model."
43)
44
45gr_interface.launch()