Created
October 14, 2011 18:18
-
-
Save iizukak/1287876 to your computer and use it in GitHub Desktop.
Gram-Schmidt Orthogonization using Numpy
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 numpy as np | |
def gs_cofficient(v1, v2): | |
return np.dot(v2, v1) / np.dot(v1, v1) | |
def multiply(cofficient, v): | |
return map((lambda x : x * cofficient), v) | |
def proj(v1, v2): | |
return multiply(gs_cofficient(v1, v2) , v1) | |
def gs(X): | |
Y = [] | |
for i in range(len(X)): | |
temp_vec = X[i] | |
for inY in Y : | |
proj_vec = proj(inY, X[i]) | |
temp_vec = map(lambda x, y : x - y, temp_vec, proj_vec) | |
Y.append(temp_vec) | |
return Y | |
#Test data | |
test = np.array([[3.0, 1.0], [2.0, 2.0]]) | |
test2 = np.array([[1.0, 1.0, 0.0], [1.0, 3.0, 1.0], [2.0, -1.0, 1.0]]) | |
print np.array(gs(test)) | |
print np.array(gs(test2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are working solely with vectors, then there is no problem with any number of dimensions (assuming you have sufficiently many linearly independent vectors to form an orthonormal basis).
This should be fine even if you are using an MxNxP (matrix/tensor, whatever). In that case you'd be able to use vectors of length MP or NP. Just have some mapping from the interval [1,MP] to a "2D" slice of the "3D" object.
For instance, take phi: x -> (x // M, x % M) [or something like it] to map x, the index into the vector, to i.j the indices in the slice.
phi would then just fill rows or columns (depending on whether you're using a row-major convention or not).
Linearity shouldn't be compromised by the method you use to traverse the "lower-dimensional" slice.