Created
May 31, 2017 18:58
-
-
Save minhlab/3df76e011e2f5dc98a9166f6ece6ef0b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| 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