Suraj442917/Spam_Detection_LogisticRegressionModel
0
1 2import torch3import torch.nn as nn4import torch.optim as optim5import gradio as gr6from sklearn.feature_extraction.text import CountVectorizer7from sklearn.model_selection import train_test_split8 9 10data = [11 ("Congratulations! You've won a free iPhone! Click here to claim.", 1),12 (" You've won money 500 dollar and 600 dollar", 1),13 ("Hey, how are you doing today?", 0),14 ("Urgent! Your account has been compromised. Reset your password now!", 1),15 ("Let's meet for coffee tomorrow.", 0),16 ("Exclusive offer just for you! Buy one get one free.", 1),17 ("Can you send me the report by today?", 0),18 ("Win a brand new car! Limited time offer.", 1),19 ("Don't forget to bring your ID to the meeting.", 0),20 ("Free vacation package! Book now and save 70%!", 1),21 ("Limited time deal: Get your free trial today!", 1),22 ("Reminder: Your bill is due next week.", 0),23 ("Alert! Unusual activity detected on your account. Verify immediately.", 1),24 ("Update: Meeting rescheduled to 3 PM.", 0),25 ("Act fast! Clearance sale up to 90% off on all items.", 1),26 ("New message from your friend: Let's catch up soon.", 0),27 ("Earn money from home easily with this simple trick.", 1),28 ("Your subscription will expire soon. Renew now to continue service.", 0),29 ("Breaking news: Celebrity scandal shocks the internet.", 1),30 ("Please review the attached document and provide feedback.", 0),31 ("You've been pre-approved for a low interest loan!", 1),32 ("Dinner plans for tonight? Let me know your thoughts.", 0),33 ("Claim your exclusive discount now. Offer expires in 24 hours!", 1),34 ("Don't miss out on this limited time opportunity.", 1),35 ("Meeting agenda for tomorrow's conference call.", 0),36 ("Your account will be suspended if you don't update your billing info.", 1),37 ("Happy Birthday! Wishing you a wonderful day.", 0),38 ("Congratulations, you have been selected for a cash prize!", 1),39 ("Just checking in to see if you received my last email.", 0),40 ("Risk-free investment opportunity! Double your money in a week!", 1),41 ("Let's finalize our plans for the weekend.", 0),42 ("Save big on your next purchase. Click to reveal your discount code.", 1),43 ("Important: Security update available for your device.", 0),44 ("You're invited to our exclusive members-only event. RSVP now!", 1),45 ("FYI: The project deadline has been extended.", 0),46 ("Get rich quick! Discover the secret to unlimited wealth.", 1),47 ("Lunch at the new cafe downtown?", 0),48 ("Unlock your potential earnings with this once-in-a-lifetime opportunity.", 1),49 ("Family reunion this summer. Looking forward to seeing you!", 0),50 ("Don't wait! Limited stock available for our best-selling product.", 1),51 ("Can we reschedule our meeting to next week?", 0),52 ("Boost your credit score instantly with our proven method.", 1),53 ("See you at the gym later?", 0),54 ("Hot deal: Save up to 50% on premium products today only!", 1),55 ("Reminder: Your appointment is confirmed for tomorrow at 10 AM.", 0),56 ("Double your income with our simple work-from-home program.", 1),57 ("Good luck with your presentation today!", 0),58 ("Exclusive invitation: Join our VIP club and enjoy special benefits.", 1),59 ("Are you available for a quick call this afternoon?", 0)60]61 62 63texts, labels = zip(*data)64 65vectorizer = CountVectorizer()66X = vectorizer.fit_transform(texts).toarray()67 68X_tensor = torch.tensor(X, dtype=torch.float32)69y_tensor = torch.tensor(labels, dtype=torch.float32).view(-1, 1)70 71X_train, X_test, y_train, y_test = train_test_split(X_tensor, y_tensor, test_size=0.2, random_state=42)72 73 74class LogisticRegressionModel(nn.Module):75 def __init__(self, input_dim):76 super(LogisticRegressionModel, self).__init__()77 self.linear = nn.Linear(input_dim, 1)78 79 def forward(self, x):80 return torch.sigmoid(self.linear(x))81 82 83input_dim = X.shape[1]84print(input_dim)85model = LogisticRegressionModel(input_dim)86model.load_state_dict(torch.load("model.pth"))87 88 89 90# Gradio UI function91def predict_spam(message):92 new_X = vectorizer.transform([message]).toarray()93 new_X_tensor = torch.tensor(new_X, dtype=torch.float32)94 with torch.no_grad():95 pred = model(new_X_tensor)96 pred = (pred >= 0.5).float().item()97 return "Spam" if pred == 1 else "Not Spam"98 99 100demo = gr.Interface(fn=predict_spam, inputs="text", outputs="text", title="Spam Detector", description="Enter a message to check if it's spam or not.")101demo.launch()102 