Python Notebooks - Perceptron and ADALINE from Scratch
In questa pagina 5
The algorithms of Halfspaces and the Perceptron AlgorithmA perceptron computes h(x) = sign(w^T x) where x includes a constant coordinate x0 = 1 that absorbs the threshold into the bias weight w0; its decision boundary is the hyperplane w^T x = 0 (a line in the plane, x2 = -(w1/w2) x1 - w0/w2). The Perceptron Learning Algorithm scans the data and, on every misclassified point, replaces w by w + y x. A single perceptron cannot separate the exclusive-or pattern; two perceptrons feeding a third give a multilayer network.Halfspaces and the Perceptron Algorithm → and 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 → as written in the course notebooks. The samples come from the generators of 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 →.
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 cell by cell with the indentation restored by hand; no output is quoted.
1. Perceptron with Python lists
Dataset as a list of lists [x_0, x_1, x_2, y] (the first coordinate is the bias input, always 1):
# create dataset [(x_0, x_1, x_2, y), ...]
dataset = [[1, 3, 1, -1],
[1, 1, 2, 1],
[1, 2.5, 2, -1],
[1, 1, 4, -1]]# vector (list) of the parameters of the model [w_0, w_1, w_2]
w = [0.0, 0.0, 0.0]
#w = [2.1, 1.4, -0.5]
# hyper-parameters (iterations)
num_iter = 50# repeat until no errors are found (or maximum number of iterations)
while True:
print("number of iterations = ", num_iter)
# number of errors
num_errors = 0
# for each element in the dataset
for elem in dataset:
# get class of element
y = elem[3]
# get coordinates
x = elem[:3]
# compute output h(x) = \sum_i w_i * x_i
output = (w[0] * x[0]) + (w[1] * x[1]) + (w[2] * x[2])
# compare output of h(x) with f(x)
if (output >= 0 and y < 0) or (output < 0 and y > 0):
# update parameters
w[0] = w[0] + (x[0] * y)
w[1] = w[1] + (x[1] * y)
w[2] = w[2] + (x[2] * y)
# update number of errors
num_errors += 1
# update iterations
num_iter -= 1
# exit while loop if
if (num_errors == 0) or (num_iter == 0):
break
print(w)Reading: each pass over the dataset is one iteration; a point is a mistake when the sign of the output disagrees with the label (an output exactly counts as "positive"); the update is the rule . The loop ends when a whole pass has no mistake or after num_iter passes (the stopping rule that protects against non-separable data).
2. Perceptron with plots of the lines
Data and initial weights (here the third point has label ):
import matplotlib.pyplot as plt
# create dataset (x_0, x_1, x_2, y)
dataset = [[1, 3.4, 1.0, -1],
[1, 1.5, 2.2, -1],
[1, 3.6, 2.4, 1],
[1, 1.7, 3.6, -1]]
# initialize weights
w = [-1.0, -1.0, 1.0]
# stopping rule
steps = 1000Plot of the data and of the initial line. The line is solved for (the notebook has this derivation in a markdown cell: w2 y = -w1 x - w0, so y = -w1/w2 x - w0/w2):
fig = plt.figure()
#ax = plt.axes()
plt.grid(linewidth = .5)
plt.plot([item[1] for item in dataset if item[3] == 1], [item[2] for item in dataset if item[3] == 1], 'v');
plt.plot([item[1] for item in dataset if item[3] == -1], [item[2] for item in dataset if item[3] == -1], 's');
plt.xlim(-5, 5)
plt.ylim(-5, 5)
x1 = -5 * (-w[1]/w[2]) - w[0]/w[2]
x2 = +5 * (-w[1]/w[2]) - w[0]/w[2]
plt.plot([-5, 5], [x1, x2], color='grey', linewidth = 1, linestyle = "--")Training, drawing every intermediate line in grey and the final one in black:
fig = plt.figure()
#ax = plt.axes()
plt.grid(linewidth = .5)
plt.plot([item[1] for item in dataset if item[3] == 1], [item[2] for item in dataset if item[3] == 1], 'v');
plt.plot([item[1] for item in dataset if item[3] == -1], [item[2] for item in dataset if item[3] == -1], 's');
plt.xlim(-5, 5)
plt.ylim(-5, 5)
x1 = -5 * (-w[1]/w[2]) - w[0]/w[2]
x2 = +5 * (-w[1]/w[2]) - w[0]/w[2]
plt.plot([-5, 5], [x1, x2], color='grey', linewidth = 1, linestyle = "--")
# set checkpoint
num_errors = 0
while True:
for datapoint in dataset:
x = datapoint[:3]
y = datapoint[3]
output = 0
dot_prod = (w[0] * x[0]) + (w[1] * x[1]) + (w[2] * x[2])
# print(dot_prod)
if (dot_prod >= 0 and y < 0) or (dot_prod <= 0 and y >= 0):
w[0] = w[0] + (x[0] * y)
w[1] = w[1] + (x[1] * y)
w[2] = w[2] + (x[2] * y)
num_errors += 1
#print(w)
#print("number of errors = ", num_errors)
x1 = -5 * (-w[1]/w[2]) - w[0]/w[2]
x2 = +5 * (-w[1]/w[2]) - w[0]/w[2]
plt.plot([-5, 5], [x1, x2], color='grey', linewidth = 0.5);
if num_errors == 0:
break
else:
num_errors = 0
steps = steps - 1
if steps == 0:
print("step zero")
break
plt.plot([-5, 5], [x1, x2], color='black', linewidth = 1);Observation from the code: here the mistake condition is (dot_prod >= 0 and y < 0) or (dot_prod <= 0 and y >= 0), so when the output is exactly a point is always a mistake, whichever its label; in the list version an output is a mistake only for .
3. Perceptron with NumPy
Data generation (two classes of 10 points; class along a diagonal, class in a small cluster) and a random initial line:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(22)
# generate 10 points per class
N = 10
X1_1 = 2 * np.random.normal(loc=0.5, scale=0.1, size=N)
X2_1 = X1_1 + np.random.normal(loc = 0, scale = 0.15, size=N) + 0.1
Y1 = np.ones(N)
X1_2 = 2*np.random.normal(loc=0.6, scale=0.05, size=N)
X2_2 = np.random.normal(loc=0.6, scale=0.07, size=N) #X1 * 2 + np.random.normal(loc = 0, scale = 0.1, size=N)
Y2 = -np.ones(N)
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
# generate w_0,....,w_n
w = np.random.uniform(low=-1,size=3)
print(w)
plt.plot([np.min(X1_1), np.max(X1_1)], [np.min(X1_1) * (-w[1]/w[2]) - w[0]/w[2], np.max(X1_2) * (-w[1]/w[2]) - w[0]/w[2]])The data matrix with the column of ones and the label vector:
X0 = np.ones(N * 2)
#X0 = X0[:, np.newaxis]
X1 = np.concatenate((X1_1, X1_2))
X2 = np.concatenate((X2_1, X2_2))
X = np.stack((X0, X1, X2), axis=1)
Y = np.concatenate((Y1, Y2))
#X = np.hstack((X0, np.vstack((X1, X2))))
plt.scatter(X[:, 1], X[:, 2], c=Y)
Y.shape[0]np.stack(..., axis=1) puts the three vectors as the columns of (); c=Y colours the points by label.
Training with a learning rate eta and an epoch counter:
w_init = w
# set checkpoint
num_errors = 0
# check epochs
epochs = 0
# set learning rate 0 < eta <= 1
eta = 1e+0
while True:
epochs += 1
for i in range(Y.shape[0]):
x = X[i, :]
y = Y[i]
#print(x, y)
dot_prod = np.dot(w, x)
#print(dot_prod * y)
if ((dot_prod * y) < 0):
w = w + eta * (x * y)
num_errors += 1
if (num_errors == 0):
break
else:
num_errors = 0
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
print(eta)
#print(num_errors)
print(epochs)
plt.plot([np.min(X1), np.max(X1)], [np.min(X1) * (-w[1]/w[2]) - w[0]/w[2], np.max(X1) * (-w[1]/w[2]) - w[0]/w[2]])The notebook that adds the experiment on the learning rate restarts from w = w_init and repeats the loop with eta = 1e+3, iterating with for x, y in zip(X, Y): instead of the index; it prints eta and epochs for each run so the two numbers of epochs can be compared. The part that changes:
w = w_init
# set checkpoint
num_errors = 0
# check epochs
epochs = 0
# set learning rate 0 < eta <= 1
eta = 1e+3
while True:
epochs += 1
for x, y in zip(X, Y):
dot_prod = np.dot(w, x)
if ((dot_prod * y) < 0):
w = w + eta * (x * y)
num_errors += 1
if (num_errors == 0):
break
else:
num_errors = 0Observations from the code (not from outputs): the mistake test is dot_prod * y < 0, so a point with output exactly is not a mistake; starting from w = 0 the loop would never update (the notebook starts from random weights). The comment says but the experiment uses ; since the update only rescales the added vector, the course leaves the effect of to be observed by the student (compare the printed epochs).
4. ADALINE with batch gradient descent
Larger data set (100 points per class) and a helper for the error:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(22)
# generate N points per class
N = 100
X1_1 = 2 * np.random.normal(loc=0.5, scale=0.1, size=N)
X2_1 = X1_1 + np.random.normal(loc = 0, scale = 0.15, size=N) + 0.1
# generate labels
Y1 = np.ones(N)
X1_2 = 2 * np.random.normal(loc=0.6, scale=0.07, size=N)
X2_2 = np.random.normal(loc=0.6, scale=0.07, size=N) - 0.3 #X1 * 2 + np.random.normal(loc = 0, scale = 0.1, size=N)
# generate labels
Y2 = -np.ones(N)
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
# generate w_0,....,w_n
w = np.random.uniform(low=-1,size=3)
#w = w / np.linalg.norm(w)
print(w)
print(np.linalg.norm(w))
plt.plot([np.min(X1_1), np.max(X1_1)], [np.min(X1_1) * (-w[1]/w[2]) - w[0]/w[2], np.max(X1_2) * (-w[1]/w[2]) - w[0]/w[2]])
# generate coordinate X0
X0 = np.ones(N * 2)
#X0 = X0[:, np.newaxis]
X1 = np.concatenate((X1_1, X1_2))
X2 = np.concatenate((X2_1, X2_2))
X = np.stack((X0, X1, X2), axis=1)
y = np.concatenate((Y1, Y2))
#X = np.hstack((X0, np.vstack((X1, X2))))
plt.scatter(X[:, 1], X[:, 2], c=y)
y.shape[0]def error_sse(errors):
error = np.sum(np.square(errors)) / 2
return error(this notebook's SSE is divided by 2; the SSE of the exercises is not). Batch training: all the points contribute to each update.
#np.random.seed(43)
# generate w_0,....,w_n
w = np.random.uniform(low=-1, high=1, size=3)
#w = np.zeros(3)
# set learning rate 0 < eta < 1
eta = 0.0001
# check epochs
epochs = 0
# set maximum epochs
max_epochs = 10000
# track total error per epoch
total_error = np.zeros(max_epochs)
while (epochs < max_epochs):
#w = w / np.linalg.norm(w)
# compute current output
adaline_output = np.dot(X, w)
# compute error for each data point
errors = y - adaline_output
# compute SSE error at this epoch
total_error[epochs] = error_sse(errors)
#print(total_error[epochs])
# check if a solution is found
# print(adaline_output)
if all(adaline_output * y > 0):
break
else:
# update with w = w + delta_w
# delta_w = eta * 2/n * X^T * (y - X^T w)
delta_w = eta * 2 * np.dot(np.transpose(X), errors) / X.shape[0]
w = w + delta_w
epochs += 1
print(w)
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
#print(eta)
print("# of epochs = ", epochs)
plt.plot([np.min(X1), np.max(X1)], [np.min(X1) * (-w[1]/w[2]) - w[0]/w[2], np.max(X1) * (-w[1]/w[2]) - w[0]/w[2]])
plt.figure()
plt.plot(range(max_epochs), total_error)Reading: np.dot(X, w) is the vector of outputs of all points; errors is ; np.dot(np.transpose(X), errors) is ; the update is the rule of 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 → with the constant written out. The loop stops when all(adaline_output * y > 0) (every point on the correct side) or at max_epochs; total_error stores the SSE of each epoch and the last line plots it against the epoch number. Note that the check is made on the sign of the output, while the quantity being minimised is the squared error.
5. Stochastic gradient descent (SGD)
Markdown title of the cell: "Stochastic Gradient Descent (SGD)". The data are shuffled at every epoch and the weights are updated after every example:
#np.random.seed(43)
# generate w_0,....,w_n
w = np.random.uniform(low=-0.1, high=0.1, size=3)
#w = np.zeros(3)
# set learning rate 0 < eta < 1
eta = 0.001
# check epochs
epochs = 0
# set maximum epochs
max_epochs = 1000
# track total error per epoch
total_error = np.zeros(max_epochs)
while (epochs < max_epochs):
#w = w / np.linalg.norm(w)
# compute current output
adaline_output = np.dot(X, w)
# compute error for each data point
errors = y - adaline_output
# compute SSE error at this epoch
total_error[epochs] = error_sse(errors)
#print(total_error[epochs])
# check if a solution is found
# print(adaline_output)
if all(adaline_output * y > 0):
break
else:
# shuffle objects
rand_perm = np.random.permutation(range(y.shape[0]))
# apply permutation and update weights
for xi, yi in zip(X[rand_perm, :], y[rand_perm]):
error = (yi - np.dot(xi, w))
# update with w = w + delta_w
delta_w = eta * 2 * xi * error
w = w + delta_w
epochs += 1
print(w)
plt.scatter(X1_1, X2_1)
plt.scatter(X1_2, X2_2)
#print(eta)
print("# of epochs = ", epochs)
plt.plot([np.min(X1), np.max(X1)], [np.min(X1) * (-w[1]/w[2]) - w[0]/w[2], np.max(X1) * (-w[1]/w[2]) - w[0]/w[2]])
plt.figure()
plt.plot(range(max_epochs), total_error)np.random.permutation(range(10)) (the last cell of the notebook) shows what a random permutation of the indices looks like. Applying the same permutation to X and y keeps every row paired with its label. Compared with batch GD: one pass over the data now makes updates, each with a single example, instead of one update; the learning rate is times larger ( against ), the initial weights are drawn in a narrower range and the maximum number of epochs is instead of .
Versione ripasso
- Dataset rows
[x0=1, x1, x2, y]; weightsw=[w0,w1,w2]; . - Perceptron (lists): loop over the data; mistake if
(output >= 0 and y < 0) or (output < 0 and y > 0); updatew[i] = w[i] + x[i]*y; stop whennum_errors == 0ornum_iter == 0. - Line to plot:
x2 = -(w1/w2) * x1 - w0/w2from the two end points . - Plot version: mistake
(dot_prod >= 0 and y < 0) or (dot_prod <= 0 and y >= 0)(output is always a mistake); stopping withsteps. - NumPy:
X = np.stack((X0, X1, X2), axis=1)
if (np.dot(w, x) * y) < 0:
w = w + eta * (x * y) count epochs; stop when a pass has no mistake. dot * y < 0: output is not a mistake (start from random weights, not zeros).
- ADALINE batch:
errors = y - np.dot(X, w)
w = w + eta * 2 * np.dot(np.transpose(X), errors) / X.shape[0] stop if all(adaline_output * y > 0) or max_epochs; store the SSE per epoch (here SSE divided by 2).
- SGD:
rand_perm = np.random.permutation(range(y.shape[0])), loopzip(X[rand_perm, :], y[rand_perm]),w = w + eta * 2 * xi * (yi - np.dot(xi, w)). - Typical errors: shuffling
Xwithouty; forgetting the column of ones; confusing with (sign of the update).
Teoria collegata
- ADALINE and Gradient Descent
- Halfspaces and the Perceptron Algorithm
- Introduction to Machine Learning - Learning, Data and Tasks
- Introduction to Machine Learning - Program Map
- Python Notebooks - Exercises on Perceptron, Regression and Logistic Regression
- Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy
- The Statistical Learning Framework and Empirical Risk Minimization