File size: 3,745 Bytes
d75ea57 | 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 | # -*- coding: utf-8 -*-
"""Email_spam_calsifier
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1obsGCm8CluG_jKB59HlJAlyO5movzKD_
# IMPORT LIBRARIES
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
"""#**LOAD DATA**"""
df = pd.read_csv('/content/mail_data.csv')
# Replace null values
data = df.where((pd.notnull(df)), '')
# Convert labels
data.loc[data['Category'] == 'spam', 'Category'] = 0
data.loc[data['Category'] == 'ham', 'Category'] = 1
# Separate features and labels
x = data['Message']
y = data['Category'].astype('int')
"""#**TRAIN TEST SPLIT**
"""
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=3)
"""#**TF-IDF**"""
tfidf = TfidfVectorizer(min_df=1, stop_words='english', lowercase=True)
x_train_features = tfidf.fit_transform(x_train)
x_test_features = tfidf.transform(x_test)
"""#**SVM MODEL**"""
model = SVC()
model.fit(x_train_features, y_train)
"""#**PREDICTIONS**"""
train_pred = model.predict(x_train_features)
test_pred = model.predict(x_test_features)
"""#**EVALUATION**"""
train_acc = accuracy_score(y_train, train_pred)
test_acc = accuracy_score(y_test, test_pred)
precision = precision_score(y_test, test_pred)
recall = recall_score(y_test, test_pred)
f1 = f1_score(y_test, test_pred)
print("Training Accuracy:", train_acc)
print("Testing Accuracy:", test_acc)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
"""#**SAMPLE TEST**"""
sample = ["claim your free gift card today"]
sample_vec = tfidf.transform(sample)
result = model.predict(sample_vec)
print("\nPrediction:", "Ham" if result[0] == 1 else "Spam")
"""#**SAVE MODEL**"""
pickle.dump(model, open("email_model.pkl", "wb"))
pickle.dump(tfidf, open("email_vectorizer.pkl", "wb"))
from google.colab import files
files.download("email_model.pkl")
files.download("email_vectorizer.pkl")
"""#**BAR CHART**"""
plt.figure()
data['Category'].value_counts().plot(kind='bar')
plt.title("Spam vs Ham Emails")
plt.xlabel("Category (0=Spam, 1=Ham)")
plt.ylabel("Count")
plt.savefig("bar_chart.png")
plt.show()
"""#**CONFUSION MATRIX**"""
cm = confusion_matrix(y_test, test_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot()
plt.savefig("confusion_matrix.png")
plt.show()
"""#**ACCURACY COMPARISON**"""
plt.figure()
plt.bar(['Train Accuracy', 'Test Accuracy'], [train_acc, test_acc])
plt.title("Train vs Test Accuracy")
plt.savefig("accuracy_graph.png")
plt.show()
"""#**DOWNLOAD GRAPHS**"""
files.download("bar_chart.png")
files.download("confusion_matrix.png")
files.download("accuracy_graph.png")
!pip install streamlit pyngrok
# Commented out IPython magic to ensure Python compatibility.
# %%writefile app.py
# import streamlit as st
# import pickle
#
# model = pickle.load(open("email_model.pkl", "rb"))
# tfidf = pickle.load(open("email_vectorizer.pkl", "rb"))
#
# st.title("Email Spam Detection App")
#
# user_input = st.text_area("Type your email here:")
#
# if st.button("Predict"):
# if user_input.strip() == "":
# st.warning("Please enter some text!")
# else:
# input_features = tfidf.transform([user_input])
# prediction = model.predict(input_features)
# st.success("Ham Email " if prediction[0]==1 else "Spam Email ")
!npm install -g localtunnel
!streamlit run app.py & npx localtunnel --port 8501 |