Salta al contenuto
Note per Studenti Python Notebooks - Exercises on Perceptron, Regression and Logistic Regression Report

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). N=250N=250 points per class. X1X_1: class 1 normal with mean 0.50.5 and standard deviation 1.51.5; class 2 normal with mean 5.45.4 and standard deviation 0.50.5. X2X_2: class 1 Poisson with λ=1.5\lambda=1.5; class 2 exponential with scale 22. Labels +1+1 for class 1 and −1-1 for class 2. Before generating the data set the random seed equal to the last four digits of the student id.

python
# 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.

python
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 X0X_0) and output vector y.

python
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 w\mathbf{w} with a normal distribution with mean 00 and standard deviation (the value is missing in the statement); η=10−4\eta=10^{-4}; mini-batch of size 2020; at most 500500 epochs; save in errors_epoch the number of misclassified objects of each epoch.

python
# 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)
python
errors_epoch

Observations: the statement says at most 500500 epochs and the solution sets max_epochs = 100; np.random.randn(3) has standard deviation 11 (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.

python
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 aX3+bX2+cX+daX^3+bX^2+cX+d with a=1.5a=1.5, b=−1b=-1, c=2c=2, d=3d=3, with Gaussian noise (mean 00, standard deviation 1.51.5), sampled at the values of X1X_1 created in Problem 1.
  • 2.2 The hypothesis set is a polynomial of degree 22: generate the data set X_reg (including the bias X0X_0).
  • 2.3 Find the optimal w_reg with the closed form w=(XTX)−1XTy\mathbf{w}=(X^TX)^{-1}X^T\mathbf{y}.
  • 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 N=100N=100 objects described by X1X_1 and X2X_2: X1X_1 normal with mean −1-1 and standard deviation 0.50.5 (class 1), mean 2.52.5 and standard deviation 11 (class 2), mean 44 and standard deviation 11 (class 3); X2X_2 exponential with scale 33 (class 1), lognormal with mean 0.50.5 and standard deviation 0.50.5 (class 2), Poisson with λ=2.0\lambda=2.0 plus the constant 55 (class 3). Labels 1,2,31,2,3.

python
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) * 3

Plot of the points and data matrix (with the bias coordinate X0X_0):

python
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 +1+1 for the objects of the positive class and −1-1 for all the others.

python
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 22.

Sum of squares error. Write sse(X, y, w):

python
def sse(X, y, w):
    error = np.sum(np.square(y - np.dot(X, w)))
    return error

Train the ADALINE with mini-batch SGD. w\mathbf{w} uniform in [−1,1][-1,1], η=10−5\eta=10^{-5} (statement) and batch size 1010, at most 100100 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:

python
# 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:

python
plt.plot(range(max_epochs+1), errors_epoch)

Observations: the values in the code (eta = 1e-4, max_epochs = 1000) differ from the statement (10−510^{-5}, 100100 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 X1X_1 to create a regression problem. The output YY (the oracle) is a cubic aX3+bX2+cX+daX^3+bX^2+cX+d with a=−1a=-1, b=2b=2, c=−3c=-3, d=4d=4 plus Gaussian noise (mean 00, standard deviation 2.52.5). Suppose the hypothesis is a quadratic function: build the data matrix X_reg (remember X0X_0), then find the optimal w\mathbf{w} by the closed form.

Solution of the solved notebook:

python
# 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, '.')
python
# 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)
python
# 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 (XTX)−1(X^TX)^{-1} and the second factor is XTyX^T\mathbf{y}, 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 44 (columns up to x4x^4 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.

python
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 [−50,50][-50,50] 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.

python
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 11 and 00):

python
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)
python
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:

python
# 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:

python
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 −∑[ylog⁡y^+(1−y)log⁡(1−y^)]-\sum[y\log\hat y+(1-y)\log(1-\hat y)] 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 y−y^y-\hat y.

Versione ripasso

  • Oracle data: np.random.seed(...), np.random.normal / poisson / exponential / lognormal, labels np.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); labels np.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 uses positive_class = 2).
  • Mini-batch SGD loop: shuffle X and labels together each epoch; for j 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 with sum((y * np.sign(np.dot(X, w))) < 0).
  • Mismatches statement/code: 4 April, epochs 500500 vs 100100, std of w blank; 8 April, η\eta and epochs differ; sse recorded with unshuffled y.
  • 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 on np.linspace; check the curvature on a wider range ([−50,50][-50,50]).
  • Logistic regression: sigmoid(z) = 1.0 / (1.0 + np.exp(-z)); cost -y.dot(np.log(out)) - ((1 - y).dot(np.log(1 - out))); update w + eta * X_batch^T (y_batch - out) / batch.
  • Typical errors: shuffling X and y separately; inverting a singular XTXX^TX; reading errors_epoch of logistic regression as a count of mistakes.

Teoria collegata