Code:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Load the dataset
url = 'https://raw.githubusercontent.com/justmarkham/pycon-2016-tutorial/master/data/sms.tsv'
data = pd.read_csv(url, sep='\t', header=None, names=['label', 'message'])

# Step 2: Data preprocessing
# Convert labels to binary values: 'spam' to 1 and 'ham' (not spam) to 0
data['label'] = data['label'].map({'spam': 1, 'ham': 0})

# Step 3: Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(data['message'], data['label'], test_size=0.2, random_state=42)

# Step 4: Convert text data into numerical data using CountVectorizer
vectorizer = CountVectorizer()
X_train_vec = vectorizer.fit_transform(X_train)
X_test_vec = vectorizer.transform(X_test)

# Step 5: Train the Naive Bayes model
model = MultinomialNB()
model.fit(X_train_vec, y_train)

# Step 6: Predict on the test set
y_pred = model.predict(X_test_vec)

# Step 7: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')

# Print classification report for detailed metrics
print(classification_report(y_test, y_pred, target_names=['ham', 'spam']))

# Step 8: Function to detect spam in new messages
def detect_spam(message):
    message_vec = vectorizer.transform([message])
    prediction = model.predict(message_vec)
    return 'spam' if prediction[0] == 1 else 'ham'

# Example usage
new_message = "Congratulations! You've won a free ticket to the Bahamas. Click here to claim it."
print(f"The message: '{new_message}' is classified as: {detect_spam(new_message)}")

print("Press enter to exit")
input()

Built With

Share this project:

Updates

Submission history