Spaces:
No application file
No application file
File size: 7,911 Bytes
ceebb11 | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | import time
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
import numpy as np
import pandas as pd
import gradio as gr # NEW: Import Gradio
# --- 1. DATASET LOADING AND PREPARATION ---
# IMPORTANT: Update this path to where you saved your spam dataset CSV file
# Example path for a mounted Google Drive:
file_path = '/content/drive/MyDrive/your_project_folder/spam_collection.csv'
try:
df = pd.read_csv(file_path, encoding='latin-1')
df = df[['v1', 'v2']]
df.columns = ['label', 'message']
df['label'] = df['label'].map({'ham': 0, 'spam': 1})
emails = df['message'].values
labels = df['label'].values
print(f"Dataset loaded successfully. Total samples: {len(emails)}")
except FileNotFoundError:
print(f"WARNING: File not found at '{file_path}'. Using small mock dataset for testing.")
emails = [
"Meeting agenda for tomorrow at 10 AM. Please review the attached document.",
"Did you remember to pick up the milk and bread from the store?",
"Final project deadline is next Friday. Let's finish up the documentation.",
"A quick note to confirm our call later this afternoon regarding the budget.",
"Your recent Amazon order has been shipped and will arrive tomorrow.",
"URGENT: Your bank account has been suspended! Click this link to verify now.",
"FREE MONEY NOW! Increase your income instantly! Click here for a big surprise!",
"Congratulations! You've won a FREE iPhone! Claim your prize immediately.",
"Lose weight fast with this one weird trick! Limited time offer, don't miss out.",
"VIAGRA PILLS cheapest price and discreet shipping! Buy now from our pharmacy.",
]
labels = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
X_train, X_test, y_train, y_test = train_test_split(
emails, labels, test_size=0.3, random_state=42, stratify=labels
)
print("--- SVM Spam Classification Project ---")
print(f"Training samples: {len(X_train)}, Testing samples: {len(X_test)}\n")
# --- 2. MEMBER 1 TASK: Text Processing (TF-IDF) and Linear SVM ---
print("Task for Member 1: Linear SVM Implementation")
linear_pipeline = Pipeline([
('tfidf', TfidfVectorizer(stop_words='english', max_features=5000)),
('classifier', LinearSVC(random_state=42, dual=False))
])
start_time_linear = time.time()
linear_pipeline.fit(X_train, y_train)
training_time_linear = time.time() - start_time_linear
y_pred_linear = linear_pipeline.predict(X_test)
accuracy_linear = accuracy_score(y_test, y_pred_linear)
# --- 3. MEMBER 2 TASK: RBF Kernel Implementation, Comparison, and Speed Analysis ---
print("\nTask for Member 2: RBF SVM and Performance Analysis")
rbf_pipeline = Pipeline([
('tfidf', TfidfVectorizer(stop_words='english', max_features=5000)),
('classifier', SVC(kernel='rbf', gamma='auto', C=1.0, random_state=42))
])
start_time_rbf = time.time()
rbf_pipeline.fit(X_train, y_train)
training_time_rbf = time.time() - start_time_rbf
y_pred_rbf = rbf_pipeline.predict(X_test)
accuracy_rbf = accuracy_score(y_test, y_pred_rbf)
# --- 4. Final Comparison and Conclusion (Printed as before) ---
print("\n-------------------------------------------")
print(" FINAL PERFORMANCE SUMMARY ")
print("-------------------------------------------")
print(f"1. Linear SVM Results:")
print(f" - Accuracy: {accuracy_linear:.4f}")
print(f" - Training Time: {training_time_linear:.6f} seconds")
print(f"\n2. RBF SVM Results:")
print(f" - Accuracy: {accuracy_rbf:.4f}")
print(f" - Training Time: {training_time_rbf:.6f} seconds")
print("\nAnalysis Summary:")
if training_time_linear < training_time_rbf:
speed_diff = training_time_rbf / training_time_linear
print(f"- **Speed Comparison:** The Linear SVM was significantly faster to train ({speed_diff:.2f}x faster in this run).")
else:
print("- **Speed Comparison:** The RBF SVM was faster in this run (Note: This is rare in large datasets; time differences will grow with dataset size).")
print(f"- **Accuracy Comparison:** Linear Accuracy ({accuracy_linear:.4f}) vs RBF Accuracy ({accuracy_rbf:.4f}).")
if accuracy_rbf > accuracy_linear:
print("- **Conclusion:** The RBF kernel achieved slightly higher accuracy, but the Linear kernel provides a strong balance of performance and speed, which is critical for large text datasets.")
elif accuracy_rbf == accuracy_linear:
print("- **Conclusion:** Both models achieved the same high accuracy, confirming that the Linear kernel is often sufficient and preferred for its speed in high-dimensional text tasks.")
else:
print("- **Conclusion:** The Linear kernel was more accurate in this specific test, demonstrating that its efficiency is not always a trade-off for performance in high-dimensional feature spaces.")
print("-------------------------------------------")
# --- 5. GRADIO INTERFACE (NEW SECTION) ---
# Function that Gradio will call for prediction
def gradio_predict_spam(email_text):
if not email_text.strip():
return "Please enter an email message to classify."
# Use the Linear Pipeline for real-time prediction
prediction = linear_pipeline.predict([email_text])[0]
if prediction == 1:
return "<span style='color: red; font-size: 1.5em; font-weight: bold;'>🚨 SPAM! (High Confidence)</span>"
else:
return "<span style='color: green; font-size: 1.5em; font-weight: bold;'>✅ Not Spam (Ham)</span>"
# Create the Gradio Interface
print("\n\n--- LAUNCHING INTERACTIVE SPAM PREDICTION UI (via Gradio) ---")
print("Click the public URL below once it appears!")
# Define the Gradio interface
iface = gr.Interface(
fn=gradio_predict_spam, # The function to call for prediction
inputs=gr.Textbox(
lines=7,
placeholder="Paste your email or text message here...",
label="Email Text Input",
# Custom CSS for the input box
elem_classes=["textbox-input"]
),
outputs=gr.HTML(
label="Prediction Result",
# Custom CSS for the output box
elem_classes=["output-result"]
),
title="📧 SVM-Powered Email Spam Classifier",
description="This tool uses a trained Linear SVM model to classify whether an email is spam or not. After the model trains, you can paste text into the box below and click submit.",
theme=gr.themes.Soft(), # A more visually appealing theme
allow_flagging='never', # Disable flagging for this demo
css="""
.textbox-input {
min-height: 180px !important;
font-size: 1.1em !important;
border: 2px solid #4CAF50 !important;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
padding: 15px;
border-radius: 8px;
}
.output-result {
text-align: center;
padding: 20px;
border: 2px solid #007bff;
border-radius: 8px;
background-color: #f8f9fa;
margin-top: 20px;
}
h1 {
color: #0056b3;
font-size: 2.5em;
text-align: center;
}
p {
font-size: 1.1em;
color: #333;
text-align: center;
}
.gradio-container {
max-width: 900px;
margin: auto;
padding: 30px;
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0,0,0,0.2);
background-color: #ffffff;
}
.gradio-btn {
background-color: #007bff !important;
color: white !important;
border-radius: 8px !important;
font-size: 1.1em !important;
padding: 10px 20px !important;
}
.gradio-btn:hover {
background-color: #0056b3 !important;
}
""" # Custom CSS for a better look and feel
)
# Launch the interface
iface.launch(share=True) # share=True creates a public URL for easy access
|