Salta al contenuto
Note per Studenti Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy Report

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

python
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 [0,1)[0,1); multiplied by 5 and by 2 they become 10 values of xx in [0,5)[0,5) and 10 values of yy in [0,2)[0,2). 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").

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

python
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

python
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 =1.0=1.0 and standard deviation scale =0.2=0.2; 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.

python
y_target = 2 * x + 5

plt.scatter(x, y_target, color = "green")

A target function (here a line, y=2x+5y=2x+5) applied to the samples: this is how the exercises play the role of the "oracle" that generates the outputs from the inputs.

python
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 =0.2=0.2 (scale is the mean of the distribution); and again

python
y_target = 2 * x + 5

plt.scatter(x, y_target, color = "green")

3. Linear algebra with NumPy

A matrix times a vector:

python
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 2×32\times3, y has three entries; np.dot(x, y) multiplies each row of x by y: the first row gives 1⋅1+2⋅2+3⋅3=141\cdot1+2\cdot2+3\cdot3=14, the second (−1)⋅1+0⋅2+(−1)⋅3=−4(-1)\cdot1+0\cdot2+(-1)\cdot3=-4, so the result is the vector [14,−4][14,-4] (computed here, the notebook output was not exported). np.inner(x, y) gives the same here.

Two matrices:

python
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 2×32\times3. np.dot(x, y) is the matrix product, which needs the number of columns of x (33) to equal the number of rows of y (22): it is not defined for these shapes and NumPy signals an error. y.T is the transpose (3×23\times2); np.dot(x, y.T) is the 2×22\times2 matrix with entries "row ii of x times row jj of y": [1432−4−10]\begin{bmatrix}14&32\\-4&-10\end{bmatrix} (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:

python
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 2×32\times3 matrix with integers in {0,1,2,3}\{0,1,2,3\}. 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 wTx\mathbf{w}^T\mathbf{x}: 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

Teoria collegata