[Logistic Regression] You will implement a spam mail detector by using logistic regression
and enron data set (https://huggingface.co/datasets/SetFit/enron spam/tree/main). The origi-
nal data samples are plain texts, so a data preprocessing will be needed to convert text data to
numerical values.
4.1 [Data Reprocessing] Run “preprocessing.py” to convert text data to numerical values. It
will generate “spam ham.csv”. Please briefly explain the text vectorization process: tf-idf (Term
Frequency-Inverse Document Frequency).
4.2 [Dimensionality Reduction] Write the code “data4 2.py” to perform PCA dimensionality re-
duction on the 2000-D the data in “spam ham.csv”. We will reduce the data dimension to 50-D
and split 4, 000 data samples into train: 3, 500 and test: 500. Please save them as “train4 2.npz”
and “test4 2.npz”.
4.3 [Logistic Regression] Write the code “train4 3.py” to train a logistic regression classifier using
only NumPy library. Implement a gradient descent algorithm to find the global minimum of the
Negative Log Likelihood (NLL) function defined below. Hint: You may use a step size about
1.0e − 4 and detect convergence when the change in NNL is less than 10, but you are free to choose
your own values.
J(w) = − ln P (t|w) =
NX
n=1
−tn ln σ(wtxn) − (1 − tn) ln (1 − σ(wtxn))
4.4 [Logistic Regression] Report the train and test accuracy of your spam detector.
4.5 [Extra Points: 10 points] “mail.txt” is the text extracted from a spam email. Please test the
text using your classifier and report the result whether it is classified as a spam.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! Let's walk through each part of your assignment step-by-step. We'll cover data preprocessing, dimensionality reduction using PCA, implementing logistic regression from scratch with NumPy, evaluating the model, and finally classifying a new email. Below are detailed explanations and corresponding code snippets for each section.
4.1 [Data Reprocessing] TF-IDF Vectorization
Explanation:
Term Frequency-Inverse Document Frequency (TF-IDF) is a numerical statistic intended to reflect how important a word is to a document in a collection or corpus. It combines two metrics:
Term Frequency (TF): Measures how frequently a term appears in a document. It's usually normalized to account for the length of the document.
[
\text{TF}(t, d) = \frac{\text{Number of times term } t \text{ appears in document } d}{\text{Total number of terms in document } d}
]
Inverse Document Frequency (IDF): Measures how important a term is by considering its presence across all documents. Terms that are common across many documents have lower IDF values.
[
\text{IDF}(t) = \log\left(\frac{\text{Total number of documents}}{\text{Number of documents containing term } t + 1}\right)
]
Weighting Words: TF-IDF assigns higher weights to words that are frequent in a particular document but rare across the corpus, making them more significant for tasks like classification.
Dimensionality Reduction: By converting text to numerical vectors using TF-IDF, we can apply machine learning algorithms that require numerical input.
Implementation Steps:
Tokenization: Split text into words (tokens).
Build Vocabulary: Create a list of unique words across all documents.
Compute TF for Each Document: Count the frequency of each word in a document.
Compute IDF for Each Term: Calculate the inverse document frequency for each word in the vocabulary.
Calculate TF-IDF Vectors: Multiply the TF and IDF values to get the TF-IDF score for each term in each document.
Sample Code for TF-IDF Vectorization:
Assuming that preprocessing.py handles the above steps and outputs a CSV file spam_ham.csv where rows correspond to documents and columns correspond to TF-IDF features. Here's a high-level overview of what preprocessing.py might look like using scikit-learn:
python
# preprocessing.py
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# Load data
# Assume you have separate lists for spam and ham emails
spam_emails = [...] # List of spam email texts
ham_emails = [...] # List of ham email texts
# Labels: 1 for spam, 0 for ham
labels = [1] * len(spam_emails) + [0] * len(ham_emails)
documents = spam_emails + ham_emails
# Initialize TF-IDF Vectorizer
vectorizer = TfidfVectorizer(max_features=2000) # Limit to top 2000 features
# Fit and transform the documents
tfidf_matrix = vectorizer.fit_transform(documents)
# Convert to DataFrame
df = pd.DataFrame(tfidf_matrix.toarray())
df['label'] = labels
# Save to CSV
df.to_csv('spam_ham.csv', index=False)
Note: Ensure you have the preprocessing.py script properly handling the loading of your dataset and executing the TF-IDF vectorization.
4.2 [Dimensionality Reduction] PCA on TF-IDF Features
Objective:
Perform Principal Component Analysis (PCA) to reduce the dimensionality of the TF-IDF feature space from 2000 dimensions to 50 dimensions.
Split the data into training (3,500 samples) and testing (500 samples).
Save the split datasets as train4_2.npz and test4_2.npz.
Implementation Steps:
Load Data: Read spam_ham.csv and separate features and labels.
Apply PCA: Reduce dimensionality from 2000 to 50.
Shuffle and Split: Randomly shuffle the data and split into training and testing sets.
Save Datasets: Use NumPy's savez to store the datasets.
Code Implementation:
python
# data4_2.py
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.utils import shuffle
# Load the CSV file
df = pd.read_csv('spam_ham.csv')
# Separate features and labels
X = df.drop('label', axis=1).values # Assuming 'label' is the column name for targets
y = df['label'].values
# Apply PCA to reduce dimensions to 50
pca = PCA(n_components=50, random_state=42)
X_pca = pca.fit_transform(X)
# Shuffle the data
X_pca, y = shuffle(X_pca, y, random_state=42)
# Select first 4,000 samples
X_pca = X_pca[:4000]
y = y[:4000]
# Split into train (3,500) and test (500)
X_train = X_pca[:3500]
y_train = y[:3500]
X_test = X_pca[3500:]
y_test = y[3500:]
# Save the datasets
np.savez('train4_2.npz', X=X_train, y=y_train)
np.savez('test4_2.npz', X=X_test, y=y_test)
print("Data has been processed and saved successfully.")
Instructions to Run:
bash
python data4_2.py
Note: Ensure that spam_ham.csv is in the same directory as data4_2.py or provide the correct path.
4.3 [Logistic Regression] Implementing from Scratch Using NumPy
Objective:
Implement a logistic regression classifier using only NumPy.
Use gradient descent to minimize the Negative Log Likelihood (NLL) function.
( \sigma(z) = \frac{1}{1 + e^{-z}} ) is the sigmoid function.
( t_n ) is the target label (0 or 1).
( x_n ) is the feature vector.
( w ) is the weight vector.
Implementation Steps:
Initialize Weights: Start with small random values or zeros.
Compute Predictions: Apply the sigmoid function to ( w^T x_n ).
Compute Gradient: Derive the gradient of NLL with respect to ( w ).
Update Weights: Adjust weights using the gradient and step size.
Convergence Check: Stop when the change in NLL is below a threshold.
Code Implementation:
python
# train4_3.py
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def compute_nll(X, y, w):
z = X.dot(w)
predictions = sigmoid(z)
# To prevent log(0), add a small epsilon
epsilon = 1e-15
predictions = np.clip(predictions, epsilon, 1 - epsilon)
nll = -np.sum(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
return nll
def gradient_descent(X, y, w, learning_rate=1e-4, tol=1e-10, max_iter=100000):
N = X.shape[0]
for i in range(max_iter):
z = X.dot(w)
predictions = sigmoid(z)
error = predictions - y
gradient = X.T.dot(error)
w_prev = w.copy()
w -= learning_rate * gradient
# Compute NLL
nll = compute_nll(X, y, w)
if i % 1000 == 0:
print(f"Iteration {i}: NLL={nll}")
# Check for convergence
if np.linalg.norm(w - w_prev) < tol:
print(f"Converged at iteration {i}")
break
return w
def main():
# Load training data
data = np.load('train4_2.npz')
X_train = data['X']
y_train = data['y']
# Add bias term by appending a column of ones
X_train = np.hstack((X_train, np.ones((X_train.shape[0], 1))))
# Initialize weights to zeros
w = np.zeros(X_train.shape[1])
# Train using gradient descent
w_trained = gradient_descent(X_train, y_train, w, learning_rate=1e-4, tol=1e-10)
# Save the trained weights
np.save('weights.npy', w_trained)
print("Training complete. Weights saved to 'weights.npy'.")
if __name__ == "__main__":
main()
Explanation of the Code:
Sigmoid Function: Computes the probability prediction.
compute_nll: Calculates the Negative Log Likelihood for current predictions.
gradient_descent: Performs the gradient descent optimization to minimize NLL.
Parameters:
learning_rate: Step size for weight updates.
tol: Tolerance for convergence (based on change in weights).
max_iter: Maximum number of iterations to prevent infinite loops.
Bias Term: Added by appending a column of ones to the feature matrix X_train.
Weight Initialization: Initialized to zeros, but you can also use small random values.
Training Loop:
For each iteration, compute predictions and NLL.
Update weights based on the gradient.
Check for convergence based on the change in weights.
Instructions to Run:
bash
python train4_3.py
Note:
Adjust learning_rate, tol, and max_iter as needed based on convergence behavior.
This implementation may be slow for large datasets. Consider optimizations if necessary.
4.4 [Logistic Regression] Reporting Train and Test Accuracy
Objective:
Evaluate the trained logistic regression model on both training and testing datasets.
Report the accuracy, i.e., the proportion of correctly classified samples.
Implementation Steps:
Load Trained Weights: Load weights.npy.
Load Datasets: Load both training and testing datasets (train4_2.npz and test4_2.npz).
Add Bias Term: Ensure the bias term is added to both datasets.
Make Predictions: Use the sigmoid function and apply a threshold (e.g., 0.5) to decide class labels.
Compute Accuracy: Compare predicted labels with true labels.
Code Implementation:
python
# evaluate4_4.py
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def predict(X, w):
z = X.dot(w)
probabilities = sigmoid(z)
return (probabilities >= 0.5).astype(int)
def compute_accuracy(y_true, y_pred):
return np.mean(y_true == y_pred)
def main():
# Load trained weights
w = np.load('weights.npy')
# Load training data
train_data = np.load('train4_2.npz')
X_train = train_data['X']
y_train = train_data['y']
# Add bias term
X_train = np.hstack((X_train, np.ones((X_train.shape[0], 1))))
# Make predictions on training data
y_pred_train = predict(X_train, w)
train_accuracy = compute_accuracy(y_train, y_pred_train)
# Load testing data
test_data = np.load('test4_2.npz')
X_test = test_data['X']
y_test = test_data['y']
# Add bias term
X_test = np.hstack((X_test, np.ones((X_test.shape[0], 1))))
# Make predictions on testing data
y_pred_test = predict(X_test, w)
test_accuracy = compute_accuracy(y_test, y_pred_test)
# Report accuracies
print(f"Training Accuracy: {train_accuracy * 100:.2f}%")
print(f"Testing Accuracy: {test_accuracy * 100:.2f}%")
if __name__ == "__main__":
main()
Instructions to Run:
bash
python evaluate4_4.py
Sample Output:
code
Training Accuracy: 95.60%
Testing Accuracy: 94.80%
Note: The exact accuracy values will depend on the dataset and the convergence of the gradient descent algorithm.
4.5 [Extra Points] Classifying a New Email
Objective:
Use the trained logistic regression classifier to predict whether a new email (mail.txt) is spam or ham.
Report the classification result.
Implementation Steps:
Preprocess the New Email:
Apply the same TF-IDF vectorization used during training.
Ensure the feature vector aligns with the PCA transformation.
Load Trained Weights: Use weights.npy.
Make Prediction: Use the logistic regression model to classify the email.
Report Result: Indicate whether the email is classified as spam or ham.
Considerations:
To transform the new email text, you need access to the TfidfVectorizer and PCA objects used during training. This requires saving these objects after training and loading them during prediction.
Since the assignment specifies only using NumPy for logistic regression, we'll assume that the necessary preprocessing objects (vectorizer and pca) are saved using pickle.
Code Implementation:
First, modify preprocessing.py and data4_2.py to save the TfidfVectorizer and PCA objects.
python
# preprocessing.py (Updated)
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import pickle
# Load data
# Replace with actual data loading
spam_emails = [...] # List of spam email texts
ham_emails = [...] # List of ham email texts
# Labels: 1 for spam, 0 for ham
labels = [1] * len(spam_emails) + [0] * len(ham_emails)
documents = spam_emails + ham_emails
# Initialize TF-IDF Vectorizer
vectorizer = TfidfVectorizer(max_features=2000)
# Fit and transform the documents
tfidf_matrix = vectorizer.fit_transform(documents)
# Save the vectorizer
with open('tfidf_vectorizer.pkl', 'wb') as f:
pickle.dump(vectorizer, f)
# Convert to DataFrame
df = pd.DataFrame(tfidf_matrix.toarray())
df['label'] = labels
# Save to CSV
df.to_csv('spam_ham.csv', index=False)
python
# data4_2.py (Updated)
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.utils import shuffle
import pickle
# Load the CSV file
df = pd.read_csv('spam_ham.csv')
# Separate features and labels
X = df.drop('label', axis=1).values
y = df['label'].values
# Apply PCA to reduce dimensions to 50
pca = PCA(n_components=50, random_state=42)
X_pca = pca.fit_transform(X)
# Save the PCA object
with open('pca_model.pkl', 'wb') as f:
pickle.dump(pca, f)
# Shuffle the data
X_pca, y = shuffle(X_pca, y, random_state=42)
# Select first 4,000 samples
X_pca = X_pca[:4000]
y = y[:4000]
# Split into train (3,500) and test (500)
X_train = X_pca[:3500]
y_train = y[:3500]
X_test = X_pca[3500:]
y_test = y[3500:]
# Save the datasets
np.savez('train4_2.npz', X=X_train, y=y_train)
np.savez('test4_2.npz', X=X_test, y=y_test)
print("Data has been processed and saved successfully.")
Creating the Classification Script:
python
# classify_mail.py
import numpy as np
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import PCA
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def predict(X, w):
z = X.dot(w)
probabilities = sigmoid(z)
return (probabilities >= 0.5).astype(int)
def main():
# Load the trained weights
w = np.load('weights.npy')
# Load the vectorizer and PCA model
with open('tfidf_vectorizer.pkl', 'rb') as f:
vectorizer = pickle.load(f)
with open('pca_model.pkl', 'rb') as f:
pca = pickle.load(f)
# Read the new email text
with open('mail.txt', 'r', encoding='utf-8') as f:
email_text = f.read()
# Transform the email using the TF-IDF vectorizer
email_tfidf = vectorizer.transform([email_text]).toarray()
# Apply PCA transformation
email_pca = pca.transform(email_tfidf)
# Add bias term
email_pca = np.hstack((email_pca, np.ones(1)))
# Predict using the logistic regression model
prediction = predict(email_pca, w)[0]
# Report the result
if prediction == 1:
print("The email is classified as SPAM.")
else:
print("The email is classified as HAM.")
if __name__ == "__main__":
main()
Instructions to Run:
Ensure that mail.txt is in the same directory as classify_mail.py.
Run the classification script:
bash
python classify_mail.py
Sample Output:
code
The email is classified as SPAM.
Important Notes:
Preprocessing Consistency: It's crucial to use the same TfidfVectorizer and PCA models that were used during training to ensure consistency in feature representation.
Saving Models: We used pickle to save the TfidfVectorizer and PCA objects after fitting them on the training data. This allows us to load and apply the same transformations to new data.
Bias Term: Ensure that during classification, the bias term (column of ones) is added to the feature vector to match the training setup.
Handling Exceptions: In a production environment, you should add error handling to manage cases where mail.txt might be missing or improperly formatted.
Summary
You've successfully:
Vectorized Text Data: Converted raw text emails into numerical representations using TF-IDF.
Reduced Dimensionality: Applied PCA to compress the feature space from 2000 dimensions to 50.
Implemented Logistic Regression: Built a logistic regression classifier from scratch using NumPy and trained it using gradient descent.
Evaluated the Model: Assessed the classifier's accuracy on both training and testing datasets.
Classified New Emails: Applied the trained model to classify a new email as spam or ham.
Ensure that all scripts are run in the correct order and that necessary files are saved and loaded appropriately. Good luck with your assignment!