Building a Spam Email Classifier — Part Two (Gradient Descent)¶

About This Project¶

In this project, you will train a logistic regression classifier on artificial data. Specifically, you will implement functions to calculate the gradient of the logistic loss function and perform gradient descent. You will use the classifier in the final project to create a logistic regression classifier that can "filter" spam email messages.

Evaluation¶

This project must be successfully completed and submitted in order to receive credit for this course. Your score on this project will be included in your final grade calculation.

You are expected to write code where you see # YOUR CODE HERE within the cells of this notebook. Not all cells will be graded; code input cells followed by cells marked with # Auto-graded test cell will be graded. Upon submitting your work, the code you write at these designated positions will be assessed using an "auto-grader" that will run all test cells to assess your code. You will receive feedback from the auto-grader that will identify any errors in your code. Use this feedback to improve your code if you need to resubmit. Be sure not to change the names of any provided functions, classes, or variables within the existing code cells, as this will interfere with the auto-grader. Also, remember to execute all code cells sequentially, not just those you’ve edited, to ensure your code runs properly.

You can resubmit your work as many times as necessary before the submission deadline. If you experience difficulty or have questions about this exercise, use the Q&A discussion board to engage with your peers or seek assistance from the instructor.

Before starting your work, please review eCornell's policy regarding plagiarism (the presentation of someone else's work as your own without source credit).

Submit Code for Auto-Grader Feedback¶

Once you have completed your work on this notebook, you will submit your code for auto-grader review. Follow these steps:

  1. Save your notebook.

  2. Mark as Completed — In the blue menu bar along the top of this code exercise window, you’ll see a menu item called Education. In the Education menu, click Mark as Completed to submit your code for auto-grader/instructor review. This process will take a moment and a progress bar will show you the status of your submission.

  3. Review your results — Once your work is marked as complete, the results of the auto-grader will automatically be presented in a new tab within the code exercise window. You can click on the assessment name in this feedback window to see more details regarding specific feedback/errors in your code submission.

  4. Repeat, if necessary — The Jupyter Notebook will always remain accessible in the first tabbed window of the exercise. To reattempt the work, you will first need to click Mark as Uncompleted in the Education menu and then proceed to make edits to the notebook. Once you are ready to resubmit, follow steps one through three. You can repeat this procedure as many times as necessary.

You can also download a copy of this notebook in multiple formats using the Save and Export Notebook As option in the File menu above.

Getting Started¶

Please run the following code to initialize your Python kernel. You should be running a version of Python 3.x.

In [ ]:
import numpy as np
import pandas as pd

# Non-interactive plots
%matplotlib inline
import matplotlib.pyplot as plt

import sys
sys.path.append("/home/codio/workspace/.modules")
from helper import *

print("Python version:", sys.version.split(" ")[0])

First, let's load artificial data and visualize the classes.

In [ ]:
np.random.seed(12)
n_samples = 500
covariance = [[1, 0.25], [0.25, 1]]

class_one = np.random.multivariate_normal(mean=[0, 5], cov=covariance, size=n_samples)
class_one_labels = np.ones(n_samples)

class_two = np.random.multivariate_normal(mean=[5, 10], cov=covariance, size=n_samples)
class_two_labels = -np.ones(n_samples)

features = np.vstack((class_one, class_two))
labels = np.hstack((class_one_labels, class_two_labels))

plt.figure()

plt.title("Artificially Generated 2D Data With Binary Labels")
plt.xlabel("Feature 1", fontsize=12)
plt.ylabel("Feature 2", fontsize=12)

plt.scatter(
    features[labels == 1, 0],  # x-coordinate
    features[labels == 1, 1],  # y-coordinate
    label="Class 1 ($+1$)",
    color="blue",
    alpha=0.5,
)
plt.scatter(
    features[labels != 1, 0],  # x-coordinate
    features[labels != 1, 1],  # y-coordinate
    label="Class 2 ($-1$)",
    color="red",
    alpha=0.5,
)

plt.legend(loc="upper left")
plt.show()

Quick Refresher¶

In the last project, you implemented the functions:

  • sigmoid returns the value of the sigmoid function

$$ \sigma(z)=\frac{1}{1 + \exp(-z)} $$

  • y_pred returns a vector whose components are the predictions probabilities

$$ P(y_i = 1 | \mathbf{x}_i ; \mathbf{w}, b) = \sigma\left(y_i\left(\mathbf{w}^\top\mathbf{x}_i + b\right)\right) $$

  • log_loss returns the value of negative log likelihood ($b$ appears in the formula below because it is not a component of $\mathbf{w}$)

$$ \mathcal{L}(\mathbf{w},b) = -\sum_{i=1}^n \log \left( \sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right) \right) $$

In this project, you will use them to finish your logistic regression classifier. For the classifier, you will implement the gradient and a "training" function that does gradient descent. (Note that the log-loss function $\mathcal{L}$ is the negative log likelihood and is often abbreviated as NLL.)

Part One: Compute Gradient [Graded]¶

Implement the function gradient, which returns the first derivative with respect to w, b given X, y, w, b. Keep in mind that you have access to the sigmoid_grader function that returns $\sigma(z)$.

To implement gradient, you need to know the mathematical expression of the gradient with respect to the weight vector $\mathbf{w}$ and the bias term $b$. First, verify that the gradient of the log-loss with respect to the weight vector $\mathbf{w}$ is

$$ \frac{\partial\mathcal{L}}{\partial \mathbf{w}}=\sum_{i=1}^n -y_i \sigma \left( -y_i \left( \mathbf{w}^\top\mathbf{x}_i + b \right) \right) \mathbf{x}_i $$

Then verify that the gradient of the log-loss with respect to $b$ is

$$ \frac{\partial\mathcal{L}}{\partial b}=\sum_{i=1}^n - y_i \sigma \left(-y_i \left( \mathbf{w}^\top\mathbf{x}_i + b \right) \right) $$


Recall how you got the expression for the gradient with respect to $\mathbf{w}$ when the bias term $b$ had been absorbed into the weight vector $\mathbf{w}$. In the present scenario, the bias term has not been included as the last component of the weight vector. However, finding the gradient of $\mathcal{L}(\mathbf{w},b)$ with respect to $\mathbf{w}$ involves a very similar computation:

$$ \begin{align} \frac{\partial\mathcal{L}}{\partial \mathbf{w}} &= \frac{\partial}{\partial \mathbf{w}} \left( -\sum_{i=1}^n \log \left( \sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right) \right) \right) \\[5pt] &= - \sum_{i=1}^n \frac{\partial}{\partial \mathbf{w}} \Bigl( \log \left( \sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right) \right) \Bigr) \\[5pt] &= - \sum_{i=1}^n \frac{1}{\sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right)} \cdot \frac{\partial}{\partial \mathbf{w}} \Bigl( \sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right) \Bigr) \\[5pt] &= - \sum_{i=1}^n \frac{1}{\sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right)} \cdot \sigma' \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right) \cdot \frac{\partial}{\partial \mathbf{w}} \Bigl( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \Bigr) \\[5pt] &= - \sum_{i=1}^n \frac{\sigma' \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right)}{\sigma \left( y_i \left(\mathbf{w}^\top \mathbf{x}_i + b \right) \right)} \cdot y_i \mathbf{x}_i \end{align} $$

Since we know that $\sigma'(z)=\sigma(z)(1-\sigma(z))$ and that $1-\sigma(z) = \sigma(-z)$, our expression finally becomes

$$ \frac{\partial\mathcal{L}}{\partial \mathbf{w}} = - \sum_{i=1}^n \sigma \left( - y_i \left( \mathbf{w}^\top \mathbf{x}_i + b \right) \right) \cdot y_i \mathbf{x}_i $$

You can similarly derive the gradient with respect to $b$ as an exercise.

In [ ]:
def gradient(X, y, w, b):
    """
    Calculates the gradients of negative log-likelihood (NLL)  
    with respect to the weight vector w and the bias term b.
    Returns the tuple (w_grad, bgrad).

    Input:
        X: Data matrix of shape (n, d)
        y: n-dimensional vector of labels (+1 or -1)
        w: d-dimensional weight vector
        b: Scalar bias term

    Output:
        wgrad: d-dimensional vector (gradient vector of w)
        bgrad: Scalar (gradient of b)
    """
    n, d = X.shape
    wgrad = np.zeros(d)
    bgrad = 0.0

    # YOUR CODE HERE
    for i in range(n):
        score = np.dot(w, X[i]) + b
        factor = -y[i] * sigmoid_grader(-y[i] * score)
        wgrad += factor * X[i]
        bgrad += factor
    # END OF YOUR CODE

    return wgrad, float(bgrad)

Run the next cell to check your implementation of gradient.

In [ ]:
def grad_test1():
    """
    Check that your gradient has the correct shape
    """
    X = np.random.rand(25, 5)               # Generate random data matrix
    w = np.random.rand(5)                   # Generate random weight vector
    b = np.random.rand(1)                   # Generate random bias term
    y = (np.random.rand(25) > 0.5) * 2 - 1  # Generate labels that are all +1
    wgrad, bgrad = gradient(X, y, w, b)     # Compute your gradient
    return wgrad.shape == w.shape and np.isscalar(bgrad)


def grad_test2():
    """
    Check your gradient against our gradient
    """
    np.random.seed(1)                       # Random seed for consistency
    X = np.random.rand(25, 5)               # Generate random data matrix
    w = np.random.rand(5)                   # Generate random weight vector
    b = np.random.rand(1)                   # Generate random bias term
    y = (np.random.rand(25) > 0.5) * 2 - 1  # Generate labels that are all +1
    wgrad, bgrad = gradient(X, y, w, b)           # Compute your gradient
    wgrad2, bgrad2 = gradient_grader(X, y, w, b)  # Compute our gradient

    # Check whether the difference in gradients is small
    w_diff_small = np.linalg.norm(wgrad - wgrad2) < 1e-06
    b_diff_small = np.linalg.norm(bgrad - bgrad2) < 1e-06
    
    return w_diff_small and b_diff_small


def grad_test3():
    """
    Check your log loss against our log loss
    """
    np.random.seed(2)                       # Random seed for consistency
    X = np.random.rand(25, 5)               # Generate random data matrix
    w = np.random.rand(5)                   # Generate random weight vector
    b = np.random.rand(1)                   # Generate random bias term
    y = (np.random.rand(25) > 0.5) * 2 - 1  # Generate labels that are all +1

    w_s = np.random.rand(5) * 1e-05         # Small random step
    b_s = np.random.rand(1) * 1e-05         # Small random step

    # Compute our log loss
    ll = log_loss_grader(X, y, w, b)
    
    # Compute our log loss after taking small random step
    ll1 = log_loss_grader(X, y, w + w_s, b + b_s)

    # Compute your gradient to approximate log loss using Taylor's expansion
    wgrad, bgrad = gradient(X, y, w, b)   

    # Use Taylor's expansion to approximate your log loss after small random step
    ll2 = ll + wgrad @ w_s + bgrad * b_s

    # Check whether the difference in log loss is small
    ll_diff_small = np.linalg.norm(ll1 - ll2) < 1e-05
    
    return ll_diff_small


def grad_test4():
    """
    Check whether your logistic regression losses are close to our losses
    """
    # Get your losses (i.e., losses1)
    w1, b1, losses1 = logistic_regression_grader(features, labels, 1000, 1e-03, gradient)

    # Get our losses (i.e., losses2)
    w2, b2, losses2 = logistic_regression_grader(features, labels, 1000, 1e-03)

    # Check whether the difference in losses is small
    losses_diff_small = np.abs(losses1[-1] - losses2[-1]) < 0.1
    
    return losses_diff_small


runtest(grad_test1, "grad_test1")
runtest(grad_test2, "grad_test2")
runtest(grad_test3, "grad_test3")
runtest(grad_test4, "grad_test4")

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (grad_test1)
In [ ]:
# Auto-graded test cell worth one point (grad_test2)
In [ ]:
# Auto-graded test cell worth one point (grad_test3)
In [ ]:
# Auto-graded test cell worth one point (grad_test4)

Part Two: Weight Update of Gradient Ascent [Graded]¶

Implement logistic_regression to train your classifier using gradient descent with learning rate alpha for max_iter iterations. You have access to gradient(X, y, w, b) and log_loss_grader(X, y, w, b) functions. gradient returns wgrad, bgrad and log_loss_grader returns nll scalar. Please use a constant learning rate alpha throughout (i.e. do not decrease the learning rate).

The idea here is to iteratively update w and b:

Logistic regression pseudocode
In [24]:
def logistic_regression(X, y, max_iter, alpha):
    """
    Trains the logistic regression classifier on data X and labels y
    using gradient descent for max_iter iterations with learning rate alpha.
    Returns the weight vector, bias term, and losses at each iteration AFTER
    updating the weight vector and bias.

    Input:
        X: Data matrix of shape nxd
        y: n-dimensional vector of data labels (+1 or -1)
        max_iter: Number of iterations of gradient descent to perform
        alpha: Learning rate for each gradient descent step

    Output:
        w, b, losses
        w: d-dimensional weight vector
        b: Scalar bias term
        losses: max_iter-dimensional vector containing negative log-likelihood
                values AFTER a gradient descent in each iteration
    """
    d = X.shape[1]
    w = np.zeros(d)
    b = 0.0
    losses = np.zeros(max_iter)

    for step in range(max_iter):
        # YOUR CODE HERE
        wgrad, bgrad = gradient(X, y, w, b)
        w = w - alpha * wgrad
        b = b - alpha * bgrad
        losses[step] = log_loss_grader(X, y, w, b)
        # END OF YOUR CODE
    
    return w, b, losses

Run the next cell to check your implementation of logistic_regression.

In [25]:
def logistic_regression_test1():
    """
    Check that your trained weights and bias are close to ours
    """
    XUnit = np.array(
        [
            [-1, 1],
            [-1, 0],
            [0, -1],
            [-1, 2],
            [1, -2],
            [1, -1],
            [1, 0],
            [0, 1],
            [1, -2],
            [-1, 2],
        ]
    )
    YUnit = np.hstack((np.ones(5), -np.ones(5)))

    # Your trained weights and bias
    w1, b1, _ = logistic_regression(XUnit, YUnit, 30000, 5e-5)

    # Our trained weights and bias
    w2, b2, _ = logistic_regression_grader(XUnit, YUnit, 30000, 5e-5)

    # Check that the differences are small
    w_diff_small = np.linalg.norm(w1 - w2) < 1e-5
    b_diff_small = np.linalg.norm(b1 - b2) < 1e-5
    
    return w_diff_small and b_diff_small


def logistic_regression_test2():
    """
    Another check that your trained weights and bias are close to ours
    """
    np.random.seed(1)  # Set random seed for consistency
    X = np.vstack((np.random.randn(50, 5), np.random.randn(50, 5) + 2))
    Y = np.hstack((np.ones(50), -np.ones(50)))
    max_iter = 300
    alpha = 1e-5

    # Your trained weights and bias
    w1, b1, _ = logistic_regression(X, Y, max_iter, alpha)

    # Our trained weights and bias
    w2, b2, _ = logistic_regression_grader(X, Y, max_iter, alpha)

    # Check that the differences are small
    w_diff_small = np.linalg.norm(w1 - w2) < 1e-5
    b_diff_small = np.linalg.norm(b1 - b2) < 1e-5
    
    return w_diff_small and b_diff_small


def logistic_regression_test3():
    """
    Check that your final loss matches our final loss
    """
    np.random.seed(2)  # Set random seed for consistency
    X = np.vstack((np.random.randn(50, 5), np.random.randn(50, 5) + 2))
    Y = np.hstack((np.ones(50), -np.ones(50)))
    max_iter = 30
    alpha = 1e-5

    # Compute your final loss
    w, b, losses = logistic_regression(X, Y, max_iter, alpha)
    your_loss = losses[-1]

    # Compute our final loss (with your trained weights and bias)
    our_loss = log_loss_grader(X, Y, w, b)

    # Check that the difference is small
    loss_diff_small = np.abs(your_loss - our_loss) < 1e-09
    
    return loss_diff_small


def logistic_regression_test4():
    """
    Check that your losses decrease
    """
    np.random.seed(3)  # Set random seed for consistency
    X = np.vstack((np.random.randn(50, 5), np.random.randn(50, 5) + 2))
    Y = np.hstack((np.ones(50), -np.ones(50)))
    max_iter = 30
    alpha = 1e-5

    # Get your first loss and last loss
    _, _, losses = logistic_regression(X, Y, max_iter, alpha)
    first_loss = losses[0]
    last_loss = losses[-1]
    
    return last_loss < first_loss


runtest(logistic_regression_test1, "logistic_regression_test1")
runtest(logistic_regression_test2, "logistic_regression_test2")
runtest(logistic_regression_test3, "logistic_regression_test3")
runtest(logistic_regression_test4, "logistic_regression_test4")
Running Test: logistic_regression_test1 ... ✔ Passed!
Running Test: logistic_regression_test2 ... ✔ Passed!
Running Test: logistic_regression_test3 ... ✔ Passed!
Running Test: logistic_regression_test4 ... ✔ Passed!

Skip over the auto-graded test cells below (see Evaluation for details).

In [ ]:
# Auto-graded test cell worth one point (logistic_regression_test1)
In [ ]:
# Auto-graded test cell worth one point (logistic_regression_test2)
In [ ]:
# Auto-graded test cell worth one point (logistic_regression_test3)
In [ ]:
# Auto-graded test cell worth one point (logistic_regression_test4)

Now run your implementation on the artificial data from the top of the notebook. Check your code by plotting the values of the negative log-likelihood. Should these values increase or decrease as the number of iterations grows? Do your values move in the right direction?

You can tune max_iter and alpha to see how they affect convergence!

In [ ]:
max_iter = 10000  # Max number of iterations
alpha = 1e-4      # Learning rate

# Train the logistic regression model
final_w, final_b, losses = logistic_regression(features, labels, max_iter, alpha)

plt.figure()
plt.title("Training Loss for Logistic Regression")
plt.xlabel("Number of Iterations", fontsize=12)
plt.ylabel("Loss", fontsize=12)
plt.plot(losses)
plt.show()

Below, we'll take the final weights from the logistic solver and predict labels for the entire dataset. By plotting the results, we can get a sense of where the linear decision boundary lies.

What do you notice? What could be changed to further improve the accuracy of the classifier? (Hint: Take a look at the second video in Module 1.)

In [ ]:
# Compute predictions (Class 1 or Class 2)
scores = y_pred_grader(features, final_w, final_b)
pred_labels = (scores > 0.5).astype(int)
pred_labels[pred_labels != 1] = -1

plt.figure()

plt.title("Predicted Labels and Decision Boundary")
plt.xlabel("Feature 1", fontsize=12)
plt.ylabel("Feature 2", fontsize=12)
plt.axis([-3.3, 8.5, 1.6, 13.5])

# Plot the predictions (Class 1 or Class 2)
plt.scatter(
    features[pred_labels == 1, 0],  # x-coordinate
    features[pred_labels == 1, 1],  # y-coordinate
    label="Class 1 ($+1$)",
    color="blue",
    alpha=0.5,
)
plt.scatter(
    features[pred_labels != 1, 0],  # x-coordinate
    features[pred_labels != 1, 1],  # y-coordinate
    label="Class 2 ($-1$)",
    color="red",
    alpha=0.5,
)

# Plot the decision boundary
x = np.linspace(np.amin(features[:, 0]), np.amax(features[:, 0]), 10)
y = -(final_w[0] * x + final_b) / final_w[1]
plt.plot(x, y, "k--")

plt.legend(loc="upper left")
plt.show()
In [ ]: