Description
Problem 1: Logistic Regression (75 points)
In this problem, we’ll build a logistic regression classifier and train it on separable and non-separable data. Since it
will be specialized to binary classification, we’ve named the class logisticClassify2 . We start by creating two
binary classification datasets, one separable and the other not:
1 iris = np.genfromtxt(“data/iris.txt”,delimiter=None)
2 X, Y = iris[:,0:2], iris[:,-1] # get first two features & target
3 X,Y = ml.shuffleData(X,Y) # order randomly rather than by class label
4 X,_ = rescale(X) # rescale to improve numerical stability, speed convergence
5
6 XA, YA = X[Y<2,:], Y[Y<2] # Dataset A: class 0 vs class 1
7 XB, YB = X[Y>0,:], Y[Y>0] # Dataset B: class 1 vs class 2
For this problem, we focus on the properties of the logistic regression learning algorithm, rather than classification
performance. Thus we will not create a separate validation dataset, and simply use all available data for training.
1. For each of the two datasets, create a separate scatter plot in which the training data from the two classes is
plotted in different colors. Which of the two datasets is linearly separable? (5 points)
2. Write (fill in) the function plotBoundary in logisticClassify2.py to compute the points on the decision
boundary. In particular, you only need to make sure x2b is set correctly using self.theta . This will plot
the data & boundary quickly, which is useful for visualizing the model during training. To demonstrate your
function, plot the decision boundary corresponding to the classifier
sign( 2 + 6×1 − 1×2
)
along with dataset A, and again with dataset B. These fixed parameters should lead to an OK classifier on one
data set, but a poor classifier on the other. You can create a “blank” learner and set the weights as follows:
1 import mltools as ml
2 from logisticClassify2 import *
3
4 learner = logisticClassify2(); # create “blank” learner
5 learner.classes = np.unique(YA) # define class labels using YA or YB
6 wts = np.array([theta0,theta1,theta2]); # TODO: fill in values
7 learner.theta = wts; # set the learner’s parameters
Include the lines of code you added to the plotBoundary function, and the two generated plots. (10 points)
Homework 3 UC Irvine 1/ 3
CS 178: Machine Learning & Data Mining Fall 2020
3. Complete the logisticClassify2.predict function to make predictions for your classifier. Verify that
your function works by computing & reporting the error rate for the classifier defined in the previous part on
both datasets A and B. (Remember that we are using a fixed, hand-selected value of theta; this is chosen to
be reasonable for one data set, but not the other. So, the error rate should be about 0.06 for one dataset,
and higher for the other.) Note that in the code, the two classes are stored in the variable self.classes ,
where the first entry is the “negative” class (class 0) and the second entry is the “positive” class (class 1). You
should create different learner objects for each dataset, and use the learner.err function. Your solution
pdf should include the predict function implementation and the computed error rates. (10 points)
4. Verify that your predict and plotBoundary implementations are consistent by using plotClassify2D
with your manually constructed learner on each dataset. This will call predict on a dense grid of points,
and you should find that the resulting decision boundary matches the one you plotted previously. (5 points)
5. In the provided training code, we first transform the classes in the data Y into Y Y , with canonical labels for
the two classes: “class 0” (negative) and “class 1” (positive). Let r
(j) = x
(j)
· θ =
P
i
x
(j)
i
θi denote the linear
response of the classifier, and σ(r) equal the standard logistic function:
σ(r) =
1 + exp(−r)
−1
.
The logistic negative log-likelihood loss for a single data point j is then
Jj
(θ) = −y
(j)
logσ(x
(j)
· θ) − (1 − y
(j)
)log(1 − σ(x
(j)
· θ)),
where y
(j)
is 0 or 1.
Show that the gradient of the negative log likelihood Jj
(θ) for logistic regression can be expressed as,
∇Jj =
σ(x
(j)
· θ) − y
(j)
x
(j)
You will use this expression to implement stochastic gradient descent in the next part.
Hint: Remember that the logistic function has a simple derivative, σ
0
(r) = σ(r)(1 − σ(r)). (15 points)
6. Complete the train function to perform stochastic gradient descent on the logistic regression loss function.
This will require that you fill in:
(a) computing the linear response r
(j)
, logistic response s
(j) = σ(r
(j)
), and gradient ∇Jj
(θ) associated with
each data point x
(j)
, y
(j)
;
(b) computing the overall loss function, J =
1
m
P
j
Jj
, after each pass through the full dataset (or epoch);
(c) a stopping criterion that checks two conditions: stop when either you have reached stopEpochs epochs,
or J has changed by less than stopTol since the last epoch.
Include the complete implementation of train in your solutions. (20 points)
7. Run the logistic regression train algorithm on both datasets. Describe the parameter choices (step sizes
and stopping criteria) you use for each dataset. Include plots showing the convergence of the surrogate loss
and error rate as a function of the number of training epochs, and the classification boundary after the final
training iteration. (The included train function creates plots automatically.) (10 points)
8. Extra Credit (10 points): Add an L2 regularization term (+α
P
i
θ
2
i
) to your surrogate loss function, and
update the gradient and your code to reflect this addition. Try re-running your learner with some regularization (e.g., α = 2) and see how different the resulting parameters are. Find a value of α that gives noticeably
different results than your un-regularized learner & explain the resulting differences.
Plotting hints: The code generates plots as the algorithm runs, so you can see its behavior over time; this is
done by repeatedly clearing the plot axes via pyplot.cla() . In Jupyter, you also need to clear the Jupyter display
using IPython.display.clear_output() .
Debugging hints: Debugging machine learning algorithms can be quite challenging, since the results of the
algorithm are highly data-dependent, and often somewhat randomized (from the initialization, as well as the order
points are visited by stochastic gradient descent). We suggest starting with a small step size and verifying both
that the learner’s prediction evolves slowly in the correct direction, and that the objective function J decreases. If
that works, explore the convergence of the algorithm with larger step sizes; if not, check the computation of the
gradient and the optimization loop. It is often useful to manually step through the code, for example by pausing
after each parameter update using input() . Of course, you may also use a more sophisticated debugger.
Homework 3 UC Irvine 2/