[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 tackle each part of the spam mail detector implementation step by step.
4.1 [Data Reprocessing]
Task:
Run preprocessing.py to convert text data to numerical values. It will generate spam_ham.csv. Briefly explain the text vectorization process: tf-idf (Term Frequency-Inverse Document Frequency).
Explanation of TF-IDF Vectorization
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 is commonly used in text mining and information retrieval to convert textual data into a meaningful numerical representation for machine learning models.
Term Frequency (TF): Measures how frequently a term appears in a document. It can be normalized to prevent bias towards longer documents.
[
\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 the number of documents in which the term appears. Rare terms across documents have higher IDF scores.
[
\text{IDF}(t) = \log\left(\frac{\text{Total number of documents}}{1 + \text{Number of documents containing term } t}\right)
]
TF-IDF Score: The product of TF and IDF scores, emphasizing words that are more relevant to specific documents.
Assuming you have the preprocessing.py script, you can run it as follows:
bash
python preprocessing.py
This script will:
Read the Plain Text Data: Load the spam and ham email texts from the Enron dataset.
Preprocess the Text: Clean the text by removing punctuation, converting to lowercase, removing stop words, etc.
Vectorize the Text using TF-IDF: Convert the cleaned text into numerical feature vectors using the TF-IDF technique.
Save the Processed Data: Output the numerical vectors along with their labels into spam_ham.csv.
The resulting spam_ham.csv will have each row representing an email, with numerical features corresponding to the TF-IDF scores of terms and a label indicating whether it's spam or ham.
4.2 [Dimensionality Reduction]
Task:
Write the code data4_2.py to perform PCA dimensionality reduction on the 2000-D data in spam_ham.csv. Reduce the data dimension to 50-D and split 4,000 data samples into training: 3,500 and testing: 500. Save them as train4_2.npz and test4_2.npz.
Code: data4_2.py
python
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
def main():
# Load the dataset
data = pd.read_csv('spam_ham.csv')
# Assuming the last column is the label
X = data.iloc[:, :-1].values # Features
y = data.iloc[:, -1].values # Labels
# Perform PCA to reduce dimensions to 50
pca = PCA(n_components=50)
X_reduced = pca.fit_transform(X)
# Select first 4000 samples
X_selected = X_reduced[:4000]
y_selected = y[:4000]
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X_selected, y_selected, train_size=3500, test_size=500, random_state=42, shuffle=True
)
# Save the splits as .npz files
np.savez('train4_2.npz', X_train=X_train, y_train=y_train)
np.savez('test4_2.npz', X_test=X_test, y_test=y_test)
print("Dimensionality reduction and data splitting completed successfully.")
if __name__ == "__main__":
main()
Explanation:
Loading the Data:
The script reads spam_ham.csv using pandas.
It separates the features (X) and labels (y). Ensure that the last column in the CSV is the label.
PCA Dimensionality Reduction:
Uses Principal Component Analysis (PCA) from scikit-learn to reduce the feature dimensions from 2000 to 50.
PCA captures the most significant variance in the data with fewer components.
Selecting 4,000 Samples:
The first 4,000 samples are selected for further processing. Ensure that the dataset has at least 4,000 samples.
Splitting into Training and Testing Sets:
Splits the selected data into training (3,500 samples) and testing (500 samples) sets.
random_state=42 ensures reproducibility.
Saving the Splits:
Both training and testing sets are saved as compressed .npz files for efficient storage and loading.
Running the Script
Ensure you have the necessary libraries installed:
bash
pip install numpy pandas scikit-learn
Run the script:
bash
python data4_2.py
4.3 [Logistic Regression]
Task:
Write the code train4_3.py to train a logistic regression classifier using only the NumPy library. Implement a gradient descent algorithm to find the global minimum of the Negative Log Likelihood (NLL) function.
Convergence criteria: Change in NLL less than a threshold (e.g., ( 10^{-5} )).
Code: train4_3.py
python
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def compute_nll(w, X, y):
epsilon = 1e-15 # to prevent log(0)
predictions = sigmoid(np.dot(X, w))
predictions = np.clip(predictions, epsilon, 1 - epsilon)
nll = -np.sum(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
return nll
def compute_gradient(w, X, y):
predictions = sigmoid(np.dot(X, w))
gradient = np.dot(X.T, (predictions - y))
return gradient
def gradient_descent(X, y, learning_rate=1.0e-4, max_iters=100000, tol=1e-5):
N, D = X.shape
w = np.zeros(D) # Initialize weights
prev_nll = compute_nll(w, X, y)
for i in range(max_iters):
grad = compute_gradient(w, X, y)
w -= learning_rate * grad
current_nll = compute_nll(w, X, y)
if abs(prev_nll - current_nll) < tol:
print(f"Converged at iteration {i}")
break
if i % 1000 == 0:
print(f"Iteration {i}: NLL = {current_nll}")
prev_nll = current_nll
return w
def main():
# Load training data
data = np.load('train4_2.npz')
X_train = data['X_train']
y_train = data['y_train']
# Add bias term by appending a column of ones
X_train = np.hstack((X_train, np.ones((X_train.shape[0], 1))))
# Convert labels to binary (assuming labels are already 0 and 1)
y_train = y_train.astype(np.float64)
# Train logistic regression using gradient descent
weights = gradient_descent(X_train, y_train)
# Save the trained weights
np.save('weights.npy', weights)
print("Training completed and weights saved.")
if __name__ == "__main__":
main()
Explanation:
Sigmoid Function:
Implements the sigmoid activation function.
Negative Log Likelihood (NLL):
Computes the NLL given current weights, features, and labels. epsilon ensures numerical stability by preventing log(0).
Gradient Calculation:
Computes the gradient of the NLL with respect to the weights.
Gradient Descent Implementation:
Initializes weights to zero.
Iteratively updates weights by moving against the gradient.
Checks for convergence by comparing the change in NLL.
Prints progress every 1,000 iterations for monitoring.
Main Function:
Loads training data from train4_2.npz.
Appends a bias term (intercept) to the feature matrix.
Converts labels to float for computation.
Calls the gradient descent function to train the model.
Saves the trained weights to weights.npy.
Running the Script
Ensure you have NumPy installed:
bash
pip install numpy
Run the script:
bash
python train4_3.py
Note: Training logistic regression with gradient descent can be computationally intensive, especially with large datasets. Adjust max_iters and learning_rate as necessary based on convergence behavior.
4.4 [Logistic Regression]
Task:
Report the train and test accuracy of your spam detector.
Code to Evaluate Accuracy
Create a new script evaluate.py to compute and report the accuracy on both training and testing datasets.
python
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def predict(X, w):
probabilities = sigmoid(np.dot(X, w))
return (probabilities >= 0.5).astype(int)
def main():
# Load weights
w = np.load('weights.npy')
# Load training data
train_data = np.load('train4_2.npz')
X_train = train_data['X_train']
y_train = train_data['y_train']
X_train = np.hstack((X_train, np.ones((X_train.shape[0], 1))))
# Load testing data
test_data = np.load('test4_2.npz')
X_test = test_data['X_test']
y_test = test_data['y_test']
X_test = np.hstack((X_test, np.ones((X_test.shape[0], 1))))
# Predict on training data
y_train_pred = predict(X_train, w)
train_accuracy = np.mean(y_train_pred == y_train) * 100
print(f"Training Accuracy: {train_accuracy:.2f}%")
# Predict on testing data
y_test_pred = predict(X_test, w)
test_accuracy = np.mean(y_test_pred == y_test) * 100
print(f"Testing Accuracy: {test_accuracy:.2f}%")
if __name__ == "__main__":
main()
Explanation:
Prediction Function:
Uses the sigmoid function to compute probabilities. Assigns label 1 if probability ≥ 0.5, else 0.
Main Function:
Loads the trained weights from weights.npy.
Loads both training and testing datasets.
Appends the bias term to feature matrices.
Makes predictions on both datasets.
Computes and prints accuracy as the percentage of correct predictions.
Running the Script
Run the evaluation script:
bash
python evaluate.py
Expected Output:
code
Training Accuracy: XX.XX%
Testing Accuracy: XX.XX%
Replace XX.XX with actual accuracy values obtained after running the script.
4.5 [Extra Points: 10 points]
Task:
“mail.txt” is the text extracted from a spam email. Test the text using your classifier and report the result whether it is classified as spam.
Approach:
Preprocess mail.txt: Apply the same preprocessing steps used in preprocessing.py to convert the raw text into a TF-IDF vector.
Apply PCA Transformation: Use the PCA model fitted during data4_2.py to reduce the dimensionality to 50-D.
Append Bias Term: Add a bias term to the feature vector.
Load Trained Weights and Predict: Use the trained logistic regression weights to compute the probability and classify as spam or ham.
Code: predict_mail.py
python
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from preprocessing import preprocess_text # Assuming preprocessing.py has a function for individual text
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def main():
# Load the trained weights
w = np.load('weights.npy')
# Load the PCA model parameters (to be saved during data4_2.py)
# Modify data4_2.py to save the PCA model
# Here, we'll assume that the PCA components are saved in 'pca_components.npy'
pca_components = np.load('pca_components.npy') # shape: (2000, 50)
# Read and preprocess the mail.txt
with open('mail.txt', 'r', encoding='utf-8') as file:
mail_content = file.read()
# Preprocess the text and convert to TF-IDF vector
# Assuming preprocess_text returns a TF-IDF vector of size 2000
# This requires that you have the same TF-IDF vectorizer parameters as used in preprocessing.py
# For simplicity, you might need to use the same vectorizer object or save the vectorizer during preprocessing
tfidf_vector = preprocess_text(mail_content) # Placeholder function
# Reduce dimensionality using PCA
# Note: You'll need to center the data using the mean used in PCA during training
# Assuming mean is saved as 'pca_mean.npy'
pca_mean = np.load('pca_mean.npy')
tfidf_centered = tfidf_vector - pca_mean
reduced_vector = np.dot(tfidf_centered, pca_components)
# Append bias term
reduced_vector = np.append(reduced_vector, 1) # shape: (51,)
# Compute probability
probability = sigmoid(np.dot(reduced_vector, w))
# Classify
label = 1 if probability >= 0.5 else 0
classification = "Spam" if label == 1 else "Ham"
print(f"The email has been classified as: {classification}")
if __name__ == "__main__":
main()
Important Considerations:
Consistency in Preprocessing:
Ensure that the preprocessing steps (like vocabulary selection, TF-IDF vectorizer parameters) are consistent between training and prediction. It's often best to save the fitted TF-IDF vectorizer during training and load it during prediction.
Saving PCA Parameters:
Modify data4_2.py to save the PCA components and the mean used during transformation.
Modifying data4_2.py to Save PCA Parameters
Update the PCA section in data4_2.py:
python
# Perform PCA to reduce dimensions to 50
pca = PCA(n_components=50)
X_reduced = pca.fit_transform(X)
# Save PCA components and mean
np.save('pca_components.npy', pca.components_.T) # Shape (2000, 50)
np.save('pca_mean.npy', pca.mean_)
Implementing preprocess_text Function
In preprocessing.py, ensure you have a function to preprocess individual texts. For example:
Save the fitted TF-IDF vectorizer during preprocessing:
python
# After fitting the vectorizer in preprocessing.py
joblib.dump(vectorizer, 'tfidf_vectorizer.joblib')
Running the Prediction Script
Ensure all necessary files (weights.npy, pca_components.npy, pca_mean.npy, tfidf_vectorizer.joblib, and mail.txt) are in the working directory.
Run the script:
bash
python predict_mail.py
Expected Output:
code
The email has been classified as: Spam
or
code
The email has been classified as: Ham
Depending on the classifier's prediction.
Summary
By following the steps above:
Data Preprocessing: Converted text data into numerical TF-IDF features.
Dimensionality Reduction: Reduced feature dimensions from 2000 to 50 using PCA and split the data into training and testing sets.
Model Training: Implemented logistic regression with gradient descent using NumPy to train a spam detector.
Evaluation: Assessed the model's accuracy on both training and testing datasets.
Deployment: Enabled classification of new emails (e.g., mail.txt) as spam or ham using the trained model.
Ensure all scripts are executed in the correct order and necessary dependencies are installed. This pipeline provides a foundational approach to building a spam detector using logistic regression.