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.
Only import numpy, and explain each step
Assistant
python
import numpy as np
# Step 1: Load the training and testing data
# We'll assume that the data is stored in numpy array files:
# X_train.npy, y_train.npy, X_test.npy, y_test.npy
# X_train and X_test are of shape (n_samples, n_features)
# y_train and y_test are of shape (n_samples,)
# Load training data
X_train = np.load('X_train.npy')
y_train = np.load('y_train.npy')
# Load testing data
X_test = np.load('X_test.npy')
y_test = np.load('y_test.npy')
# Step 2: Define the sigmoid function
def sigmoid(z):
"""
Compute the sigmoid function σ(z) = 1 / (1 + exp(-z))
"""
return 1 / (1 + np.exp(-z))
# Step 3: Initialize the weights
# We initialize weights w to zeros, shape (n_features,)
n_features = X_train.shape[1]
w = np.zeros(n_features)
# Step 4: Set parameters for gradient descent
learning_rate = 1e-4 # Step size
max_iterations = 100000 # Maximum number of iterations
tolerance = 10 # Tolerance for convergence based on change in NLL
# Step 5: Implement gradient descent algorithm
# We will store the previous NLL to check for convergence
prev_nll = float('inf')
for iteration in range(max_iterations):
# Compute linear combination of inputs and weights
z = np.dot(X_train, w) # Shape (n_samples,)
# Compute predictions using sigmoid function
y_pred = sigmoid(z) # Shape (n_samples,)
# Compute Negative Log Likelihood (NLL) cost function
# NLL = −∑ [ t_n * ln(σ(w^T x_n)) + (1 − t_n) * ln(1 − σ(w^T x_n)) ]
# Adding small epsilon to prevent log(0)
epsilon = 1e-15
nll = -np.sum(y_train * np.log(y_pred + epsilon) + (1 - y_train) * np.log(1 - y_pred + epsilon))
# Check for convergence
if abs(prev_nll - nll) < tolerance:
print(f'Converged at iteration {iteration}')
break
prev_nll = nll
# Compute gradient of NLL with respect to weights
# Gradient: ∇J(w) = X^T (σ(Xw) - y)
gradient = np.dot(X_train.T, y_pred - y_train) # Shape (n_features,)
# Update weights using gradient descent rule
w -= learning_rate * gradient
# Step 6: After training, compute train and test accuracy
def predict(X, w):
"""
Predict labels for given data X and weights w.
Returns binary labels (0 or 1)
"""
z = np.dot(X, w)
y_pred = sigmoid(z)
return (y_pred >= 0.5).astype(int)
# Compute train accuracy
y_train_pred = predict(X_train, w)
train_accuracy = np.mean(y_train_pred == y_train)
print(f'Training Accuracy: {train_accuracy * 100:.2f}%')
# Compute test accuracy
y_test_pred = predict(X_test, w)
test_accuracy = np.mean(y_test_pred == y_test)
print(f'Test Accuracy: {test_accuracy * 100:.2f}%')
# Step 7: Test the classifier on 'mail.txt'
# Load vocabulary mapping (assuming it's stored in 'vocab.npy')
# vocab is a dictionary mapping words to indices in the feature vector
vocab = np.load('vocab.npy', allow_pickle=True).item() # vocab is a dictionary {word: index}
# Function to process text and convert to feature vector
def text_to_feature_vector(text, vocab):
"""
Convert a text string into a feature vector based on the vocabulary.
"""
# Initialize feature vector of zeros
feature_vector = np.zeros(len(vocab))
# Preprocess text: lowercasing and splitting into words
words = text.lower().split()
# Update the feature vector
for word in words:
if word in vocab:
index = vocab[word]
feature_vector[index] += 1 # Count occurrence
return feature_vector
# Read 'mail.txt'
with open('mail.txt', 'r') as f:
mail_text = f.read()
# Convert the mail text to feature vector
X_mail = text_to_feature_vector(mail_text, vocab)
# Predict whether it's spam or not
y_mail_pred = predict(X_mail.reshape(1, -1), w) # Reshape to (1, n_features)
if y_mail_pred[0] == 1:
print("The email is classified as SPAM.")
else:
print("The email is classified as NOT SPAM.")
Explanation of Each Step:
Importing Necessary Library:
We import only numpy as required.
Loading Data:
We load training and testing datasets which are assumed to be stored as NumPy arrays in .npy files.
X_train, y_train are training features and labels, respectively.
X_test, y_test are testing features and labels, respectively.
Defining Sigmoid Function:
The sigmoid function computes the logistic sigmoid, which is essential in logistic regression to map predictions to probabilities between 0 and 1.
Initializing Weights:
We initialize the weight vector w with zeros. The size of w is equal to the number of features in our dataset.
Setting Gradient Descent Parameters:
We set the learning rate (step size) and the maximum number of iterations for the gradient descent algorithm.
A tolerance level is set to determine convergence when the change in the Negative Log Likelihood (NLL) is less than this value.
Gradient Descent Algorithm:
We iterate over the dataset to update weights using gradient descent.
Computing Predictions:
For each iteration, we compute the linear combination z = X_train * w and pass it through the sigmoid function to get the predicted probabilities y_pred.
Computing NLL:
We compute the Negative Log Likelihood (NLL) to quantify the error between predicted probabilities and actual labels.
A small epsilon value is added to prevent taking the log of zero.
Checking for Convergence:
If the change in NLL is less than the specified tolerance, we consider the algorithm has converged and break the loop.
Computing Gradient:
We compute the gradient of the NLL with respect to the weights.
The gradient tells us the direction in which we should update our weights to minimize the NLL.
Updating Weights:
This code provides a complete implementation of logistic regression using gradient descent to minimize the Negative Log Likelihood, without using any libraries other than NumPy. Each step is carefully explained, and end-to-end functionality including training, testing, and classification of new data is provided.
Dataset releases
Not yet included in a published release.
We update the weights by taking a step opposite to the gradient direction scaled by the learning rate.
Computing Accuracy:
After training, we use the predict function to classify the training and testing data.
The accuracy is computed by comparing the predicted labels with the actual labels.
Testing on 'mail.txt':
We load a vocabulary mapping, which maps words to feature indices.
We read the content of 'mail.txt' and convert it into a feature vector using the same method as for the training data.
We predict whether the email is spam or not using the trained weights.