Spaces:
Sleeping
Sleeping
File size: 1,358 Bytes
73a393b 924d4e1 73a393b 924d4e1 |
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 |
import gradio as gr
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 1. Load dataset
dataset = load_dataset("ucirvine/sms_spam", split="train")
texts = dataset["sms"]
labels = [1 if label == "spam" else 0 for label in dataset["label"]] # spam=1, ham=0
# 2. Train/test split
X_train, X_test, y_train, y_test = train_test_split(texts, labels, test_size=0.2, random_state=42)
# 3. Create model pipeline (TF-IDF + Naive Bayes)
model = make_pipeline(TfidfVectorizer(), MultinomialNB())
model.fit(X_train, y_train)
# 4. Accuracy for reference
y_pred = model.predict(X_test)
print("Validation Accuracy:", accuracy_score(y_test, y_pred))
# 5. Gradio interface
def predict_spam(message):
pred = model.predict([message])[0]
return "π© Not Spam (Ham)" if pred == 0 else "π« Spam"
iface = gr.Interface(
fn=predict_spam,
inputs=gr.Textbox(lines=4, label="Enter your SMS message"),
outputs=gr.Text(label="Prediction"),
title="π¬ SMS Spam Detector",
description="Classifies whether an SMS message is spam or not using a Naive Bayes model."
)
if __name__ == "__main__":
iface.launch(share=False)
|