Due: Wednesday, November 11 at 11:59 PM
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.
In this homework we will be analyzing two datasets:
Download and extract the HW07 starter code from Piazza. You should have the following files:
data/ — directory containing train/test datasets.run_LR.py — your main program executable for Logistic Regression.LogisticRegression.py — functions for your Logistic Regression implementation.README.md — for analysis questions and homework feedback.test_hw07.py — public tests you can run while implementing your solution.requirements.txt — Python dependencies.HW07_written_problems_student.pdf - Problem set worksheetUse Python 3.10 or newer and install the dependencies:
python3 -m pip install -r requirements.txt
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
To simplify preprocessing, you may assume the following:
parse_csv() reads these headerless files and returns NumPy
arrays: features of shape (n, p) and labels of shape (n,).challenger_orig.csv includes dates and a header. It is provided for
reference; use challenger_train.csv and challenger_test.csv for your experiments.alpha value of type float.
The provided argument parser checks this requirement.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.
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.
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.
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:
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:
np.random.default_rng(seed) generator created before
the loop, and iterate through rng.permutation(n) each epoch. Using the
same index for X and y preserves their pairing.tmax epochs, or when
the absolute change in cost between two completed epochs is strictly less
than eps. Compare costs starting with the second epoch. Always complete
the first epoch; eps=0 disables early stopping.eps=1e-4, tmax=1000, and seed=0. You can change these
with --eps, --tmax, and --seed when running the driver.ValueError, as described in the starter docstrings.Choose hyperparameters using training-only validation, then report test performance. Avoid choosing parameters by repeatedly evaluating the test set.
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.
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.
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.
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.
Answer these questions in README.md:
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.