holehouse.org Blog Machine learning notes

Appendix 1: Python and NumPy

A note on this chapter

Arrays and shapes

import numpy as np

A = np.array([[1402,  191],
              [1371,  821],
              [ 949, 1437],
              [ 147, 1448]])

A.shape       # (4, 2)  -> a [4 x 2] matrix

v = np.array([460, 232, 315, 178])
v.shape       # (4,)    -> a 1-D array of 4 numbers
v.reshape(4, 1).shape  # (4, 1)  -> an explicit column vector

A 1-D array has no orientation — it is neither a row nor a column until you reshape it. For most of the code in these notes the 1-D form is fine.

The operations the notes lean on

X = np.array([[1, 2104],
              [1, 1416],
              [1, 1534],
              [1,  852]])          # data with a column of 1s, as in chapter 03
theta = np.array([-40, 0.25])

X @ theta     # [486., 314., 343.5, 173.]  -> one prediction per row
X.T.shape     # (2, 4)   -> the transpose
X[:, 1] - X[:, 1].mean()   # mean normalization of a feature, in one line
(X[:, 1] > 1500)            # [ True, False,  True, False]  -> boolean mask

Vectorization

The toolbox used in later chapters

from scipy.optimize import minimize

def cost_function(theta):        # returns (cost, gradient)
    jval = ((theta - 5) ** 2).sum()
    gradient = 2 * (theta - 5)
    return jval, gradient

res = minimize(cost_function, np.zeros(2), jac=True)
res.x         # [5., 5.]  -> the minimum, found for us

The same worked example chapter 06 uses to introduce advanced optimization — J(θ) = (θ1 − 5)² + (θ2 − 5)², minimised at (5, 5).