Skip to main content

Homework 7: Logistic Regression and Visualization

Due: Wednesday, November 11 at 11:59 PM

Overview

Goals:

Credit: Materials by Sara Mathieson, modified from material created by Ameet Soni. Phoneme dataset and information created by Jessica Wu. Challenger dataset and visualization ideas from Alvin Grissom.

Introduction

In this homework we will be analyzing two datasets:

Download and extract the HW07 starter code from Piazza. You should have the following files:

Use Python 3.10 or newer and install the dependencies:

python3 -m pip install -r requirements.txt

Usage and I/O

Usage

Your program takes the training and testing filenames and a parameter for the learning rate alpha. For example, to run Logistic Regression on the phoneme example:

python3 run_LR.py -r data/phoneme_train.csv -e data/phoneme_test.csv -a 0.02

Program Inputs

To simplify preprocessing, you may assume the following:

Program Outputs

Your program should print the confusion matrix and accuracy for both the phoneme and Challenger datasets. Rows of the confusion matrix are the true labels; columns are the predicted labels, ordered 0 then 1.

Use good top-down design principles so your code is readable. The starter provides typed function signatures for the cost, SGD, logistic function, and prediction helpers. Complete the nine TODO functions in LogisticRegression.py and run_LR.py, keeping their signatures and type annotations. Add annotations and docstrings to any helpers you introduce. The CSV reader, argument parser, and main experiment driver are provided; you must also add the sklearn comparison described below.

Logistic Regression

You will implement the logistic regression task discussed in class for binary classification. Implement the model yourself using NumPy for arithmetic; do not use a library classifier for this part.

Model

Assume the features are continuous and the response is a discrete, binary output. In the case of binary labels, the probability of a positive prediction is:

\[h_{\vec{w}}(\vec{x})=p(y=1\mid\vec{x})=\frac{1}{1+e^{-\vec{w}\cdot\vec{x}}}\]

To model the intercept, include a bias term: a feature that is always “on”. For this starter, prepend a 1 to each feature vector using add_ones(). The first weight is the learned intercept. Training and prediction receive raw features and add the bias exactly once; logistic() receives an already augmented feature vector.

Implement logistic() using the dot product. For numerical stability, if z = x dot w is nonnegative, use 1/(1+exp(-z)); otherwise use exp(z)/(1+exp(z)). This avoids overflow for large positive or negative scores.

Training

To learn the weights, apply stochastic gradient descent (SGD) until the cost function changes very little between iterations. Our cost is the negative log of the likelihood function, where the likelihood is:

\[L(\vec{w})=\prod_{i=1}^{n}h_{\vec{w}}(\vec{x}_i)^{y_i}(1-h_{\vec{w}}(\vec{x}_i))^{1-y_i}\]

Implement costJ() as the sum of negative log likelihoods, using natural logs:

\[J(\vec{w})=-\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]\]

Clip probabilities to [1e-15, 1-1e-15] before computing the logarithms. Use this same cost for stopping. No regularization is required.

Use the same idea as in HW03 for linear regression:

initialize weights to zeros
while not converged:
    shuffle the training examples
    for each training example xi:
        calculate the derivative of the cost
        weights = weights - alpha * derivative
    compute the current cost

The SGD updates are:

\[\vec{w}\leftarrow\vec{w}-\alpha\left(h_{\vec{w}}(\vec{x}_i)-y_i\right)\vec{x}_i\]

The hyperparameter alpha is passed to SGD and used in training. A few notes:

Choose hyperparameters using training-only validation, then report test performance. Avoid choosing parameters by repeatedly evaluating the test set.

Prediction

For binary prediction, apply the same logistic equation to obtain p(y=1 | x) and output the more likely binary outcome.

Implement prediction() to return a NumPy array of probabilities, threshold() to assign class 1 when the probability is at least 0.5, and accuracy() to return the fraction correct. Empty accuracy input must raise ValueError. Prediction uses the learned weights without training again. Implement confusion_matrix() in run_LR.py as well.

The choice of hyperparameters affects the results. Aim for at least 90% accuracy on the phoneme testing data, and report and explain your actual result. Make sure to print a confusion matrix. Challenger has just one test example, so its accuracy is not a reliable estimate of generalization.

Example Output

The original lab gives this example run for testing purposes, with no shuffling, alpha 0.02, and epsilon 1e-4:

$ python3 run_LR.py -r data/phoneme_train.csv -e data/phoneme_test.csv -a 0.02
Accuracy: 0.875000 (70 out of 80 correct)

   prediction
      0  1
    ------
  0| 36  4
  1|  6 34

This illustrates the output and matrix orientation, not an exact target. Your final implementation must shuffle. The provided driver prints the matrix as a NumPy array and also prints the weights and probabilities.

Comparison with sklearn

After implementing logistic regression yourself, use the LogisticRegression model implemented in scikit-learn. Train and evaluate it on both datasets and compare its results with your own implementation. Add this code yourself in the if args.compare: block in run_LR.py. The starter provides the --compare flag, but leaves the comparison unimplemented.

Import sklearn’s classifier, create and fit a model using only training features and labels, and evaluate it on the test data. Report accuracy, confusion matrix, and positive-class probabilities. Keep your own model and the sklearn model separate. Record the sklearn settings you choose, including regularization and the iteration limit. Once implemented, run the comparison:

python3 run_LR.py -r data/phoneme_train.csv -e data/phoneme_test.csv -a 0.02 --compare

Record both models’ accuracy and confusion matrix for both datasets in README.md. Discuss differences in optimization, regularization, stopping, and feature scales. The coefficients need not be identical.

Visualization

For just the Challenger dataset, create a visualization of both:

Implement plot_challenger() in run_LR.py. Plot the fitted probabilities on a sorted, dense temperature grid spanning both splits. Use temperature in °F on the horizontal axis and damage indicator / predicted probability on the vertical axis. Save the figure and close it; do not call show(). Reject data with more than one feature.

Think about the visualization practices discussed in class:

Save your figure using the filename challenger.pdf. For example:

python3 run_LR.py -r data/challenger_train.csv -e data/challenger_test.csv -a 0.0001 --tmax 10000 --eps 0 --compare --plot challenger.pdf

This is an initial experiment setting, not a guarantee of convergence. Raw temperatures can make SGD converge slowly; inspect your training results and discuss this in the comparison. If you introduce scaling, fit the scaling on training data only and transform test inputs and the plotting grid consistently.

The model predicts the dataset’s O-ring damage indicator, which is not the same as a catastrophic accident. The 31°F prediction is outside the observed training temperature range. Consider this extrapolation and the limited data when interpreting the fitted model.

Analysis

Answer these questions in README.md:

  1. Are there any differences between your implementation of logistic regression and the sklearn model? How did the sklearn model perform on the datasets? Include the settings, accuracies, and confusion matrices.
  2. So far, we have run logistic regression and Naive Bayes on different types of datasets. Why is that? Discuss the types of features and labels that we worked with in each case.
  3. Regarding the Challenger data specifically, what was your final predicted probability of O-ring damage after fitting the model? Is this what you expected? Based on the available evidence, would you have recommended Challenger be launched on 1/28/86? What data and/or modeling might have helped increase confidence in the prediction? Distinguish damage from a catastrophic accident and discuss extrapolation.

Testing and submission

Run the public tests from the homework directory:

python3 -m unittest -v test_hw07

The 13 public tests illustrate the function contracts. They initially fail until you implement the TODOs; passing them does not guarantee full credit.

Submit a ZIP to HW07 on Gradescope with these files at the root:

LogisticRegression.py
run_LR.py
README.md
challenger.pdf
HW07_written_problems_student.pdf

Do not submit the datasets.