Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy
In questa pagina 3
First practical notebook of the course (empirical study of random variables). The language itself is in Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics → and Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →; the probability behind the densities in Gaussian Random Vectorsa gaussian vector is defined as an affine transformation of a vector of i.i.d. standard normals, so it is identified by its mean vector and covariance matrix, has a density only when the covariance matrix is invertible, stays gaussian under affine maps, and has independent components exactly when they are uncorrelated.Gaussian Random Vectors → and Central Limit Theoremthe standardized arithmetic mean of iid random variables with finite variance converges in distribution to N(0,1), whatever the distribution of the variables, which justifies the Gaussian approximation of sums.Central Limit Theorem →. The samples are used in the exercises of Python Notebooks - Exercises on Perceptron, Regression and Logistic RegressionThe exercise notebooks of the course: generating two- and three-class data with NumPy distributions, training an ADALINE/perceptron by mini-batch stochastic gradient descent and plotting the errors per epoch, polynomial regression by the closed form w = (X^T X)^{-1} X^T y on a data matrix with columns 1, x, x^2, and logistic regression trained by mini-batch gradient descent on the log loss. Statement and solution code are given, with the inconsistencies between statement and code pointed out.Python Notebooks - Exercises on Perceptron, Regression and Logistic Regression → and in 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 (one space for every level) and the outputs (numbers and figures) are missing. The code below is reproduced cell by cell with the indentation restored by hand; no output is quoted unless computed here.
1. Random samples and line and scatter plots
import numpy as np
#np.random.seed(123)
x = 5 * np.random.rand(10)
y = 2 * np.random.rand(10)np.random.rand(10) returns 10 numbers drawn uniformly from ; multiplied by 5 and by 2 they become 10 values of in and 10 values of in . The commented np.random.seed(123) fixes the generator so that the same numbers are produced at each run (used in all exercises: "set the random seed").
import matplotlib.pyplot as plt
plt.plot(x, y,
color = 'red',
linewidth = 0.1,
linestyle = '--',
marker = '.')plt.plot draws the points joined by a line; the options set colour, line width, line style and marker.
plt.plot(x, y, color = 'red', linewidth = 0.5, linestyle = ':', marker = '.')
plt.scatter(x, y, color = 'yellow')plt.scatter draws only the points (this is the call used for the data of the classification exercises).
2. Normal and exponential samples against their density
from scipy.stats import norm
x = np.random.normal(loc = 1.0, scale = 0.2, size = 100)
y = norm.pdf(x, loc = 1.0, scale = 0.2)
plt.hist(x, density = True, alpha = 0.5)
plt.scatter(x, y, color = "red")100 samples from a normal distribution with mean loc and standard deviation scale ; norm.pdf evaluates the theoretical density at the sampled values; the histogram with density = True is normalised to area 1, so histogram and red points can be compared; alpha is the transparency.
y_target = 2 * x + 5
plt.scatter(x, y_target, color = "green")A target function (here a line, ) applied to the samples: this is how the exercises play the role of the "oracle" that generates the outputs from the inputs.
from scipy.stats import expon
x = np.random.exponential(scale = 0.2, size = 100)
y = expon.pdf(x, scale = 0.2)
plt.hist(x, density = True, alpha = 0.5)
plt.scatter(x, y, color = "red")The same for an exponential distribution with scale (scale is the mean of the distribution); and again
y_target = 2 * x + 5
plt.scatter(x, y_target, color = "green")3. Linear algebra with NumPy
A matrix times a vector:
x = np.array([[1, 2, 3], [-1, 0, -1]])
y = np.array([1, 2, 3])
y
np.dot(x, y)
np.inner(x, y)x is , y has three entries; np.dot(x, y) multiplies each row of x by y: the first row gives , the second , so the result is the vector (computed here, the notebook output was not exported). np.inner(x, y) gives the same here.
Two matrices:
x = np.array([[1, 2, 3], [-1, 0, -1]])
y = np.array(([1, 2, 3], [4, 5, 6]))
x
y
np.dot(x, y)
np.dot(x, y.T)
y.T
np.inner(x, y)Both are . np.dot(x, y) is the matrix product, which needs the number of columns of x () to equal the number of rows of y (): it is not defined for these shapes and NumPy signals an error. y.T is the transpose (); np.dot(x, y.T) is the matrix with entries "row of x times row of y": (computed here). np.inner(x, y) of two 2-D arrays is the product of rows of x with rows of y, i.e. the same matrix as np.dot(x, y.T).
The same questions on random integer matrices:
A = np.random.randint(4, size = (2,3))
B = np.random.randint(4, size = (2,3))
print("A = \n", A)
print("B = \n", B)
np.dot(A, B)
np.inner(A, B)
C = np.random.randint(4, size = (1,3))np.random.randint(4, size = (2,3)) fills a matrix with integers in . The cell np.dot(A, B) has the shape problem of the previous example; np.inner(A, B) works. In the perceptron code the same operation is the product : np.dot(w, x) for two vectors, and np.dot(X, w) for the data matrix (see 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 →).
Versione ripasso
Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy
- Samples:
np.random.rand(n)uniform in ;np.random.normal(loc, scale, size);np.random.exponential(scale, size)(scaleis the mean);np.random.randint(4, size=(2,3));np.random.seed(123)fixes them. - Plots:
plt.plot(x, y, color, linewidth, linestyle, marker)joins the points;plt.scatter(x, y)draws only the points. - Histogram against density:
norm.pdf(x, loc, scale)fromscipy.stats;plt.hist(x, density=True, alpha=0.5)is normalised to area 1, so it is comparable with the density points. - Oracle:
y_target = 2 * x + 5generates the outputs from the inputs. - Matrix times vector:
np.dot(x, y)multiplies each row ofxbyy; forx= [[1,2,3],[-1,0,-1]],y= [1,2,3] it gives . - Two matrices:
np.dot(x, y)needs the columns ofxto equal the rows ofy; for two arrays it fails.np.dot(x, y.T)(transpose) gives for the second example;np.inner(A, B)works on arrays. - Perceptron code uses
np.dot(w, x)andnp.dot(X, w)(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 →). - Background: Central Limit Theoremthe standardized arithmetic mean of iid random variables with finite variance converges in distribution to N(0,1), whatever the distribution of the variables, which justifies the Gaussian approximation of sums.Central Limit Theorem →, Gaussian Random Vectorsa gaussian vector is defined as an affine transformation of a vector of i.i.d. standard normals, so it is identified by its mean vector and covariance matrix, has a density only when the covariance matrix is invertible, stays gaussian under affine maps, and has independent components exactly when they are uncorrelated.Gaussian Random Vectors →; language: Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics →.
- Typical errors: wrong shapes in
np.dot; forgettingdensity=Truewhen comparing histogram and density; forgetting.Tfor the transpose.