Learning Machines

Taught by Patrick Hebron at ITP, Fall 2015


Linear Algebra in Python and Numpy (Part 1):


Documentation:

Importing Numpy library:

import numpy as np

Array Creation:

>>> np.array( [ 0, 2, 4, 6, 8 ] )
array([0, 2, 4, 6, 8])

>>> np.zeros( 5 )
array([ 0.,  0.,  0.,  0.,  0.])

>>> np.ones( 5 )
array([ 1.,  1.,  1.,  1.,  1.])

>>> np.zeros( ( 5, 1 ) )
array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]])

>>> np.zeros( ( 1, 5 ) )
array([[ 0.,  0.,  0.,  0.,  0.]])

>>> np.arange( 5 )
array([0, 1, 2, 3, 4])

>>> np.arange( 0, 1, 0.1 )
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

>>> np.linspace( 0, 1, 5 )
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ])

>>> np.random.random( 5 )
array([ 0.22035712,  0.89856076,  0.46510509,  0.36395359,  0.3459122 ])

Vector Addition:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> b = np.array( [ 10.0, 20.0, 30.0, 40.0, 50.0 ] )
>>> a + b
array([ 11.,  22.,  33.,  44.,  55.])

Vector Subtraction:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> b = np.array( [ 10.0, 20.0, 30.0, 40.0, 50.0 ] )
>>> a - b
array([ -9., -18., -27., -36., -45.])

Hadamard Product:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> b = np.array( [ 10.0, 20.0, 30.0, 40.0, 50.0 ] )
>>> a * b
array([  10.,   40.,   90.,  160.,  250.])

Dot Product:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> b = np.array( [ 10.0, 20.0, 30.0, 40.0, 50.0 ] )
>>> np.dot( a, b )
550.0

Vector-Scalar Addition:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> a + 3.14
array([ 4.14,  5.14,  6.14,  7.14,  8.14])

Vector-Scalar Subtraction:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> a - 3.14
array([-2.14, -1.14, -0.14,  0.86,  1.86])

Vector-Scalar Multiplication:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> a * 3.14
array([  3.14,   6.28,   9.42,  12.56,  15.7 ])

Vector-Scalar Division:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> a / 3.14
array([ 0.31847134,  0.63694268,  0.95541401,  1.27388535,  1.59235669])

Magnitude:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> np.linalg.norm( a )
7.416198487095663

Normalization:

>>> a = np.array( [  1.0,  2.0,  3.0,  4.0,  5.0 ] )
>>> a / np.linalg.norm( a )
array([ 0.13483997,  0.26967994,  0.40451992,  0.53935989,  0.67419986])