Lists aren't vectors =/ We need to help them become such.

Element wise addition


In [1]:
def vector_add(v, w):
    '''adds two vectors element by element'''
    return [v_i + w_i
           for v_i, w_i in zip(v,w)]

In [2]:
a = [1,2,3]
b = [5,6,7]

In [3]:
vector_add(a,b)


Out[3]:
[6, 8, 10]

Subtraction


In [4]:
def vector_subtract(v, w):
    '''subtracts element by element'''
    return [v_i - w_i
           for v_i, w_i in zip(v,w)]

In [5]:
vector_subtract(a,b)


Out[5]:
[-4, -4, -4]

Vector Sum


In [6]:
# we can sum an arbitrary number of vectors with reduce
def vector_sum(vectors):
    return reduce(vector_add, vectors) # combine vectors with rule vector_add

In [7]:
vector_sum([a,b,a,b])


Out[7]:
[12, 16, 20]

Scalar mult


In [8]:
def scalar_multiply(c, v):
    '''Takes scalar c and multiplies it by vector v'''
    return [c * v_i for v_i in v]

In [9]:
scalar_multiply(4,a)


Out[9]:
[4, 8, 12]

Well now I can do a mean


In [10]:
from __future__ import division
def vector_mean(vectors):
    '''elementwise mean of a collection of vectors'''
    n = len(vectors)
    return scalar_multiply(1/n, vector_sum(vectors))

In [11]:
vector_mean([a,b])


Out[11]:
[3.0, 4.0, 5.0]

Dot Product


In [12]:
def dot(v, w):
    '''We want the sum of the element wise products'''
    return sum(v_i * w_i
               for v_i,w_i in zip(v,w))

In [13]:
dot(a,b)


Out[13]:
38

Sum of Squares


In [14]:
def sum_of_squares(v):
    '''Simply the self dot product'''
    return dot(v,v)

In [15]:
sum_of_squares(a)


Out[15]:
14

Magnitude


In [16]:
import math

def magnitude(v):
    return math.sqrt(sum_of_squares(v))

In [17]:
magnitude(a)


Out[17]:
3.7416573867739413

Distance between two vectors then


In [18]:
# This is the sum of squares of the difference vector
def squared_distance(v, w):
    return sum_of_squares(vector_subtract(v, w))

# Which allows us to calc the distance
def distance(v,w):
    return math.sqrt(squared_distance(v, w))

# More directly, the magnitude of the difference vector
def distance(v,w):
    return magnitude(vector_subtract(v, w))

In [19]:
distance(a,b)


Out[19]:
6.928203230275509

Matrices


In [20]:
# Shape
def shape(A):
    num_rows = len(A)
    num_cols = len(A[0]) if A else 0
    return num_rows, num_cols

In [21]:
A = [[1,2,3],
    [4,5,6]]

B = [[2,4],
    [6,8],
    [10,12]]

In [22]:
shape(A)


Out[22]:
(2, 3)

In [23]:
shape(B)


Out[23]:
(3, 2)

In [24]:
def get_row(A, i):
    return A[i]

def get_column(A, j):
    return [A_i[j]
           for A_i in A]

In [30]:
def make_matrix(num_rows, num_cols, make_fn):
    return [[make_fn(i, j)
            for j in xrange(num_cols)]
            for i in xrange(num_rows)]

def is_diagonal(i, j):
    '''1s on diag 0 otherwise'''
    return 1 if i == j else 0

In [31]:
make_matrix(4,4, is_diagonal)


Out[31]:
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

In [ ]: