Skip to content

Instantly share code, notes, and snippets.

@minhlab
Created May 31, 2017 18:58
Show Gist options
  • Select an option

  • Save minhlab/3df76e011e2f5dc98a9166f6ece6ef0b to your computer and use it in GitHub Desktop.

Select an option

Save minhlab/3df76e011e2f5dc98a9166f6ece6ef0b to your computer and use it in GitHub Desktop.
import numpy as np
import sys
def zero_safe_normalization(a):
norms = np.sum(a*a, axis=1)
zero_indices = np.nonzero(norms == 0)[0].tolist()
if zero_indices:
sys.stderr.write('Detect %d zero norms: %s\n' %(len(zero_indices), str(zero_indices)))
norms[zero_indices] = 1.0 # don't worry, 0/1 = 0
a /= norms[:,np.newaxis]
if __name__ == '__main__':
test_matrix = np.random.rand(10, 5)
test_matrix[7] = 0.0
zero_safe_normalization(test_matrix)
print(test_matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment