Skip to content

Instantly share code, notes, and snippets.

@shandysulen
Created December 4, 2018 05:31
Show Gist options
  • Select an option

  • Save shandysulen/04607a35b709156c5c956bd7684e39c7 to your computer and use it in GitHub Desktop.

Select an option

Save shandysulen/04607a35b709156c5c956bd7684e39c7 to your computer and use it in GitHub Desktop.
The following Gram-Schmidt orthogonalization procedure implementation is modified to use the city-block or manhattan-distance metric (instead of the typical Euclidean distance metric) so as to preserve the nature of any rational vectors input into the function.
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
from numpy import linalg
from functools import reduce
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import urllib.request
def norm1(v):
"""
Returns the L1 (city-block, manhattan distance, taxicab) norm
"""
return np.sum(np.absolute(v))
def proj(v, G):
"""
This function finds the projection of vector v onto the line, plane,
hyperplane, etc. formed by the orthonormal vectors within G. Because we're
working with orthonormal bases, proj(v,g) = (v ⋅ g)g.
Returns the projection of v onto g.
"""
return (np.dot(v, G[0]) * G[0]) if len(G) == 1 else reduce(lambda a,b : (np.dot(v, a) * a) + (np.dot(v, b) * b), G)
def gs(W):
"""
Takes in a finite set of vectors and generates an orthonormal basis.
"""
G = []
i = 1
for w in W:
if G == []:
g = np.divide(w, norm1(w))
G.append(g)
else:
g = w - proj(w, G)
g = np.divide(g, norm1(g))
G.append(g)
print(i)
i += 1
return G
# 1. Load Jimmi Hendrix image
img = mpimg.imread("hendrix_final.png")
print(img.shape)
# 2. Extract red color channel (2000 x 2000 matrix)
red_img = (img[0:len(img), 0:len(img), 0])
plt.imshow(red_img)
plt.show()
# 3. Perform modified Gram-Schmidt on rows of image
reduced_red_img = gs(red_img)
# 4. Show reduced_red_img
plt.imshow(reduced_red_img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment