Python Notebooks - Exercises on Perceptron, Regression and Logistic Regression
In questa pagina 3
Exercise notebooks that apply ADALINE and Gradient DescentADALINE is a perceptron whose activation function is the identity: during training the unit outputs w^T x and the in-sample error E_in = (1/N) sum (y_i - w^T x_i)^2 is minimised by gradient descent, w_new = w_old - eta * grad E_in, with partial derivatives dE_in/dw_j = (2/N) sum (y_i - w^T x_i)(-x_i^j) and matrix form grad E_in proportional to -X^T (Y - X w). The prediction is still the sign of w^T x. Learning rate eta sets the step size and a stopping rule ends the iteration.ADALINE and Gradient Descent →, Linear RegressionIn linear regression the hypothesis is h(x) = w^T x and the in-sample error is E_in(w) = (1/N) sum (w^T x_i - y_i)^2 = (1/N) times the squared norm of (Xw - Y), with X the N-row data matrix. Setting the gradient (2/N) X^T (Xw - Y) to zero gives the normal equations X^T X w = X^T Y and the closed-form solution w = (X^T X)^{-1} X^T Y, where (X^T X)^{-1} X^T is the pseudo-inverse of X; only a small square matrix (number of features) has to be inverted. Polynomial regression is the same formula on a data matrix with columns 1, x, x^2, ...Linear Regression → and Logistic RegressionLogistic regression models the probability p of the positive class: the logit (log of the odds p/(1-p)) is assumed linear in the input, logit(p) = w^T x = z. Inverting it gives p = 1/(1 + e^(-z)), the logistic sigmoid; an object goes to class 1 when the sigmoid exceeds 0.5, i.e. when z > 0. The parameters are learned by maximising the Bernoulli log-likelihood, equivalently minimising the cost J = -y log(yhat) - (1 - y) log(1 - yhat), by gradient descent with gradient (1/m) X^T (h(x) - y).Logistic Regression →. In these exercises the student plays the role of the oracle: he or she generates the data from known distributions. Generators: Python Notebooks - Random Samples, Plots and Linear Algebra with NumPyThe first course notebook draws random samples with NumPy (uniform with np.random.rand, normal and exponential), plots them with matplotlib (line and scatter plots, histograms compared with the theoretical density from scipy.stats), and shows the NumPy products used later: np.dot and np.inner between a matrix and a vector and between two matrices, with the transpose. This note reproduces the code of the notebook "matplotlib, random numbers and statistics" with the meaning of each call.Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy →. Basic algorithms: Python Notebooks - Perceptron and ADALINE from ScratchCode of the course notebooks that implement the Perceptron Learning Algorithm first with Python lists, then with plots of the successive lines, then with NumPy arrays (data matrix X with a column of ones, update w + eta * y * x on mistakes, epoch counter), and finally ADALINE: batch gradient descent with delta_w = eta * 2 * X^T (y - X w) / N and the stochastic version that shuffles the data and updates after every example. Differences between the versions (condition for a mistake, learning rate, stopping rule) are pointed out.Python Notebooks - Perceptron and ADALINE from Scratch →.
Note on the source. In the copies of the notebooks available for these notes the indentation of the code is flattened and the outputs are missing; the code is reproduced with the indentation restored by hand. Empty answer cells of the unsolved parts are not reproduced.
1. Exercise of 4 April: perceptron and regression
Problem 1: classification
Statement. Implement a single layer neural network (perceptron) and evaluate it on a classification problem with two classes C1 and C2, each object described by two features X1 and X2.
Exercise 1.1 (play the oracle). points per class. : class 1 normal with mean and standard deviation ; class 2 normal with mean and standard deviation . : class 1 Poisson with ; class 2 exponential with scale . Labels for class 1 and for class 2. Before generating the data set the random seed equal to the last four digits of the student id.
# write your answer here
import numpy as np
# set random seed
np.random.seed(123)
# generate N points per class
N=250
# draw samples for X1
X1_1 = np.random.normal(loc=0.5, scale=1.5, size = N)
X1_2 = np.random.normal(loc= 5.4, scale=0.5, size =N)
# draw samples for X2
X2_1 = np.random.poisson(lam=1.5, size=N)
X2_2 = np.random.exponential(scale=2, size=N)
# set labels
y1 = np.ones(N)
y2 = -np.ones(N)Exercise 1.2. Scatter plot of the two classes.
import matplotlib.pyplot as plt
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)Exercise 1.3. Matrix of points X (one row per object, do not forget the bias ) and output vector y.
X = np.stack((np.ones(N*2),
np.concatenate((X1_1, X1_2)),
np.concatenate((X2_1, X2_2))),
axis=1)
y = np.concatenate((y1,y2))Exercise 1.4. Train a perceptron with a mini-batch stochastic gradient descent: initialise with a normal distribution with mean and standard deviation (the value is missing in the statement); ; mini-batch of size ; at most epochs; save in errors_epoch the number of misclassified objects of each epoch.
# generate w_0,....,w_n
w = np.random.randn(3)
# set learning rate
eta = 1e-4
# set mini-batch size
batch_size= 20
# set max epochs
max_epochs = 100
# set errors per epoch
errors_epoch = np.zeros(max_epochs)
# start training
for epoch in range(max_epochs):
# compute number of errors
errors_epoch[epoch] = sum((y * np.sign(np.dot(X, w))) < 0)
# generate random permutations
rand_perm = np.random.permutation(range(y.shape[0]))
X = X[rand_perm, :]
y = y[rand_perm]
for j in range(0, y.shape[0], batch_size):
X_batch = X[j:(j+ batch_size), :]
y_batch = y[j:(j+batch_size)]
errors = y_batch - np.dot(X_batch, w)
w = w + eta * np.dot(np.transpose(X_batch), errors)
errors_epoch[epoch] = sum((y * np.sign(np.dot(X, w))) < 0)errors_epochObservations: the statement says at most epochs and the solution sets max_epochs = 100; np.random.randn(3) has standard deviation (the statement leaves it blank). The number of errors is counted with y * np.sign(X w) < 0: the zero-one loss of The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization →. The update is the ADALINE mini-batch step without division by the batch size. The cell after the loop overwrites the last entry of errors_epoch with the count after the last update.
Exercise 1.5. Two plots: data with the separating line, and the number of errors per epoch.
fig, axs = plt.subplots(1, 2, figsize=(15, 5), sharey=False)
axs[0].scatter(X[:, 1], X[:, 2], c=y)
axs[0].plot([np.min(X[:, 1]), np.max(X[:, 1])], [np.min(X[:, 1]) * (-w[1]/w[2]) - w[0]/w[2], np.max(X[:, 1]) * (-w[1]/w[2]) - w[0]/w[2]], c= "red")
axs[1].plot(range(max_epochs), errors_epoch)Problem 2: regression (closed form)
Statement. Build a closed-form solution for a regression problem.
- 2.1 The target is a cubic with , , , , with Gaussian noise (mean , standard deviation ), sampled at the values of created in Problem 1.
- 2.2 The hypothesis set is a polynomial of degree : generate the data set
X_reg(including the bias ). - 2.3 Find the optimal
w_regwith the closed form . - 2.4 Plot the points with the solution (generate a grid of points and plot the curve).
The answer cells of this notebook are empty in the source (only the comments # find closed form solution, # w = (X^T X)^-1 (X^T y), # plot points, # generate grid of points, # plot line). The solved version of the same problem is in the next section.
2. Exercise of 8 April: three classes and polynomial regression
Statement. Create a data set with three classes of objects described by and : normal with mean and standard deviation (class 1), mean and standard deviation (class 2), mean and standard deviation (class 3); exponential with scale (class 1), lognormal with mean and standard deviation (class 2), Poisson with plus the constant (class 3). Labels .
import numpy as np
np.random.seed(123)
# generate N points per class
N = 100
# generate points
X1_1 = np.random.normal(loc = -1, scale = 0.5, size = N)
X1_2 = np.random.normal(loc = 2.5, scale = 1, size = N)
X1_3 = np.random.normal(loc = 4, scale = 1, size = N)
X2_1 = np.random.exponential(scale = 3, size = N)
X2_2 = np.random.lognormal(mean = 0.5, sigma = 0.5, size = N)
X2_3 = np.random.poisson(lam = 2, size = N) + 5
y1 = np.ones(N)
y2 = np.ones(N) * 2
y3 = np.ones(N) * 3Plot of the points and data matrix (with the bias coordinate ):
import matplotlib.pyplot as plt
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
plt.scatter(X1_3, X2_3)
# stack vectors
X = np.stack((np.ones(N * 3),
np.concatenate((X1_1, X1_2, X1_3)),
np.concatenate((X2_1, X2_2, X2_3))),
axis = 1)
y = np.concatenate((y1, y2, y3))Choose a category. Train a binary classifier for one class: the label vector y_class has for the objects of the positive class and for all the others.
positive_class = 2
y_class = -np.ones(y.shape[0])
y_class[y == positive_class] = 1
plt.scatter(X[:, 1], X[:, 2], c = y_class)This turns a three-class problem into a binary one, "class against the rest" (see the per-class view in Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →). The statement says "class 3" but the code sets positive_class = 2, i.e. the positive class is the one with label .
Sum of squares error. Write sse(X, y, w):
def sse(X, y, w):
error = np.sum(np.square(y - np.dot(X, w)))
return errorTrain the ADALINE with mini-batch SGD. uniform in , (statement) and batch size , at most epochs (statement); store the SSE per epoch in sse_epoch and the misclassified objects in errors_epoch; shuffle the data set at every epoch. Code of the notebook:
# generate w_0,....,w_n
w = np.random.uniform(low = -1, high = 1, size = 3)
#X = np.hstack((X0, np.vstack((X1, X2))))
plt.scatter(X[:, 1], X[:, 2], c=y_class)
# set learning rate 0 < eta <= 1
eta = 1e-4
# set mini batch size
batch_size = 10
# set max epochs
max_epochs = 1000
# track total error per epoch
sse_epoch = np.zeros(max_epochs + 1)
# set checkpoint
errors_epoch = np.zeros(max_epochs + 1)
for epochs in range(max_epochs):
# compute error
sse_epoch[epochs] = sse(X, y, w)
errors_epoch[epochs] = sum(y_class * np.sign(np.dot(X, w)) < 0)
# generate random permutation
rand_perm = np.random.permutation(range(y_class.shape[0]))
X = X[rand_perm, :]
y_class = y_class[rand_perm]
# mini-batch learning
for j in range(0, y_class.shape[0], batch_size):
X_batch = X[j:(j + batch_size), :]
y_batch = y_class[j:(j + batch_size)]
errors = y_batch - np.dot(X_batch, w)
w = w + eta * np.dot(np.transpose(X_batch), errors) / X_batch.shape[0]
sse_epoch[epochs + 1] = sse(X, y_class, w)
errors_epoch[epochs + 1] = sum((y_class * np.sign(np.dot(X, w))) < 0)
#print(eta)
print("# of errors = ", errors_epoch[-1])
plt.plot([np.min(X[:, 1]), np.max(X[:, 1])],
[np.min(X[:, 1]) * (-w[1]/w[2]) - w[0]/w[2], np.max(X[:, 1]) * (-w[1]/w[2]) - w[0]/w[2]],
c = "red")Plot of the number of errors per epoch:
plt.plot(range(max_epochs+1), errors_epoch)Observations: the values in the code (eta = 1e-4, max_epochs = 1000) differ from the statement (, epochs); this version divides the update by the batch size X_batch.shape[0], the 4 April version does not. In the code, sse_epoch[epochs] is computed with y (the original three-class labels, not shuffled together with X) and not with y_class; since X is permuted at each epoch while y is not, this recorded SSE does not correspond to the binary problem, probably a slip; errors_epoch uses y_class correctly. The solved version of the same notebook (with N = 3 and batch_size = 5, a small run to inspect the arrays) has the same structure and the update w = w + eta * np.dot(np.transpose(X_batch), errors) without division; it also has X.shape and w printing cells.
Polynomial regression task
Statement. Reuse the coordinate to create a regression problem. The output (the oracle) is a cubic with , , , plus Gaussian noise (mean , standard deviation ). Suppose the hypothesis is a quadratic function: build the data matrix X_reg (remember ), then find the optimal by the closed form.
Solution of the solved notebook:
# generate (oracle) quadratic target function
y = -X[:, 1]**3 + 2 * X[:, 1]**2 - 3 * X[:, 1] + 4 + np.random.normal(loc = 0, scale = 2.5, size=X.shape[0])
# plot data
plt.plot(X[:, 1], y, '.')# create (quadratic) data matrix
X0 = np.ones(N * 3)
X_reg = np.stack((X0, X[:, 1], X[:, 1]**2), axis=1)
# create (quadratic) data matrix
#X_reg = np.stack((X0, X[:, 1], X[:, 1]**2, X[:, 1]**3, X[:, 1]**4), axis=1)# find closed form solution
# w = (X^T X)^-1 (X^T y)
w = np.dot(np.linalg.inv(np.dot(np.transpose(X_reg), X_reg)), np.dot(np.transpose(X_reg), y))
# plot points
plt.plot(X[:, 1], y, '.')
# generate grid of points
x_grid = np.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 100)
# plot line
plt.plot(x_grid, w[0] + x_grid * w[1] + x_grid**2 * w[2])
#plt.plot(x_grid, w[0] + x_grid * w[1] + x_grid**2 * w[2] + x_grid**3 * w[3] + x_grid**4 * w[4])np.linalg.inv(np.dot(X_reg.T, X_reg)) is and the second factor is , exactly the formula of Linear RegressionIn linear regression the hypothesis is h(x) = w^T x and the in-sample error is E_in(w) = (1/N) sum (w^T x_i - y_i)^2 = (1/N) times the squared norm of (Xw - Y), with X the N-row data matrix. Setting the gradient (2/N) X^T (Xw - Y) to zero gives the normal equations X^T X w = X^T Y and the closed-form solution w = (X^T X)^{-1} X^T Y, where (X^T X)^{-1} X^T is the pseudo-inverse of X; only a small square matrix (number of features) has to be inverted. Polynomial regression is the same formula on a data matrix with columns 1, x, x^2, ...Linear Regression →. The commented line shows the alternative hypothesis of degree (columns up to and the matching plot). The notebook then asks:
Check the curvature of the solution. Why does this solution look like a line? Try to plot the parabola and think about the reasons of this shape.
x_g = np.linspace(-50, 50, 100)
plt.plot(x_g, w[0] + x_g * w[1] + x_g**2 * w[2])
#plt.plot(x_g, w[0] + x_g * w[1] + x_g**2 * w[2] + x_g**3 * w[3] + x_g**4 * w[4])The question is left open in the source: the fitted parabola is first drawn only over the range of the data, then over to see its curvature.
3. Logistic regression notebook
The notebook first redraws the odds, logit and sigmoid of Logistic RegressionLogistic regression models the probability p of the positive class: the logit (log of the odds p/(1-p)) is assumed linear in the input, logit(p) = w^T x = z. Inverting it gives p = 1/(1 + e^(-z)), the logistic sigmoid; an object goes to class 1 when the sigmoid exceeds 0.5, i.e. when z > 0. The parameters are learned by maximising the Bernoulli log-likelihood, equivalently minimising the cost J = -y log(yhat) - (1 - y) log(1 - yhat), by gradient descent with gradient (1/m) X^T (h(x) - y).Logistic Regression → (cells with p = np.arange(0.01, 0.99, 0.01), odds_ratio = p / (1 - p), np.log(odds_ratio), sigmoid), then trains the model.
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
z = np.arange(-7, 7, 0.1)
phi_z = sigmoid(z)
plt.plot(z, phi_z)
plt.axvline(0.0, color='k', alpha = 0.5, linestyle = ":")
plt.axhline(0.5, color='k', alpha = 0.5, linestyle = ":")
#plt.ylim(-0.1, 1.1)
plt.xlabel('z')
plt.ylabel('sigmoid(z)')
plt.axhline(1.0, color='k', alpha = 0.1, linestyle = "--")
plt.axhline(0.0, color='k', alpha = 0.1, linestyle = "--")Data: one feature; class 1 exponential, class 0 normal (labels and ):
import numpy as np
# set random seed
np.random.seed(123)
# generate N points per class
N = 100
# draw samples for X1
X1_1 = np.random.exponential(scale = 5.5, size = N)
X1_2 = np.random.normal(loc = -2.5, scale = 1.5, size = N)
# set labels
y1 = np.ones(N)
y2 = np.zeros(N)import matplotlib.pyplot as plt
plt.scatter(X1_1, y1)
plt.scatter(X1_2, y2)
X = np.stack((np.ones(N * 2),
np.concatenate((X1_1, X1_2))),
axis = 1)
y = np.concatenate((y1, y2))Training by mini-batch gradient descent, storing the log loss of each epoch:
# generate w_0,....,w_n
w = np.random.randn(2)
# set learning rate
eta = 1e-2
# set mini-batch size
batch_size = 50
# set max epochs
max_epochs = 100
# set errors per epoch
errors_epoch = np.zeros(max_epochs)
# start training
for epochs in range(max_epochs):
# output
logreg_output = sigmoid(np.dot(X, w))
# compute the log loss
cost = (-y.dot(np.log(logreg_output)) - ((1 - y).dot(np.log(1 - logreg_output))))
errors_epoch[epochs] = cost
# compute (quantity) of error
errors = (y - logreg_output)
# generate random permutation for stochastic gradient descent
rand_perm = np.random.permutation(range(y.shape[0]))
X = X[rand_perm, :]
y = y[rand_perm]
# mini-batch learning
for j in range(0, y.shape[0], batch_size):
X_batch = X[j:(j + batch_size), :]
y_batch = y[j:(j + batch_size)]
# output
logreg_output = sigmoid(np.dot(X_batch, w))
errors = (y_batch - logreg_output)
w = w + eta * np.dot(np.transpose(X_batch), errors) / X_batch.shape[0]
print(w)Plot of the data with the fitted sigmoid and of the cost per epoch:
fig, axs = plt.subplots(1, 2, figsize=(15, 5), sharey=False)
axs[0].scatter(X1_1, y1)
axs[0].scatter(X1_2, y2)
#plt.scatter(X1_1, y1)
#plt.scatter(X1_2, y2)
zz = np.arange(-5, 10, 0.1)
xx = np.stack((np.ones(len(zz)),
zz),
axis = 1)
axs[0].plot(zz, sigmoid(np.dot(xx, w)), c = "c")
axs[1].plot(range(max_epochs), errors_epoch)Reading: cost is the log loss summed over all the objects (so it is the sum, not the average); the vector errors_epoch holds this cost, not a number of mistakes; the update is the gradient step of the logistic regression page, with the output error .
Versione ripasso
- Oracle data:
np.random.seed(...),np.random.normal / poisson / exponential / lognormal, labelsnp.ones(N),-np.ones(N). - Data matrix:
X = np.stack((np.ones(N*2), np.concatenate((X1_1, X1_2)), np.concatenate((X2_1, X2_2))), axis=1); labelsnp.concatenate((y1, y2)). - One class against the rest:
y_class = -np.ones(y.shape[0]); y_class[y == positive_class] = 1(statement says class 3, code usespositive_class = 2). - Mini-batch SGD loop: shuffle
Xand labels together each epoch; forj in range(0, N, batch_size):errors = y_batch - np.dot(X_batch, w);w = w + eta * np.dot(np.transpose(X_batch), errors)(some versions/ X_batch.shape[0]). Count errors withsum((y * np.sign(np.dot(X, w))) < 0). - Mismatches statement/code: 4 April, epochs vs , std of
wblank; 8 April, and epochs differ;sserecorded with unshuffledy. - Polynomial regression:
X_reg = np.stack((X0, X[:,1], X[:,1]**2), axis=1);w = np.dot(np.linalg.inv(np.dot(np.transpose(X_reg), X_reg)), np.dot(np.transpose(X_reg), y)); plot onnp.linspace; check the curvature on a wider range (). - Logistic regression:
sigmoid(z) = 1.0 / (1.0 + np.exp(-z)); cost-y.dot(np.log(out)) - ((1 - y).dot(np.log(1 - out))); updatew + eta * X_batch^T (y_batch - out) / batch. - Typical errors: shuffling
Xandyseparately; inverting a singular ; readingerrors_epochof logistic regression as a count of mistakes.