Last active
August 29, 2015 14:24
-
-
Save gavinwhyte/58899412fdd44f055029 to your computer and use it in GitHub Desktop.
Datascience
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
# coding=utf-8 | |
def vector_add(v,w): | |
"""adds corresponding elements""" | |
return [v_i + w_i | |
for v_i, w_i in zip(v,w)] | |
def vector_subtract(v, w): | |
"""subtracts corresponding elements""" | |
return [v_i - w_i | |
for v_i, w_i in zip(v,w)] | |
"""We’ll also sometimes want to componentwise sum a list of vectors. """ | |
def vector_sum(vectors): | |
""" vectors: sum all corresponding elements""" | |
result = vectors[0] | |
for vector in vectors[1:]: | |
result = vector_add(result, vector) | |
return result | |
# multiple a vector by a scalar | |
def scalar_multiple(c,v): | |
"""c is a number , v is a vector""" | |
return [c * v_i for v_i in v] | |
# This allows us to compute the componentwise means of a list of (same-sized) vectors: | |
def vector_mean(vectors): | |
"""compute the vector whose ith element is the mean of the | |
ith elements of the input vectors""" | |
n = len(vectors) | |
return scalar_multiple(1/n, vector_sum(vectors)) | |
# The dot product measures how far the vector v extends in the w direction. | |
def dot(v,w): | |
"""v_1 *w_1 + ... v_n * w_n""" | |
return sum(v_i * w_i | |
for v_i, w_i in zip(v,w)) | |
## Now it is easy to compute vector sum of squares | |
def sum_of_squares(v): | |
"""V_1 * v_1 + ... + v_n + v_n""" | |
return dot(v,v) | |
# Which we can use to compute its magnitude (or length): | |
def magnitude(v): | |
return math.sqrt(sum_of_squares(v)) | |
def squared_distance(v, w): | |
"""(v_1 - w_1)** 2 + ... + (v_n - w_n) ** 2 """ | |
return sum_of_squares(vector_subtract(v,w)) | |
def distance(v,w): | |
return math.sqrt(squared_distance(v,w)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment