可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I would like to have the norm of one NumPy array. More specifically, I am looking for an equivalent version of this function
def normalize(v): norm = np.linalg.norm(v) if norm == 0: return v return v / norm
Is there something like that in skearn
or numpy
?
This function works in a situation where v
is the 0 vector.
回答1:
If you're using scikit-learn you can use sklearn.preprocessing.normalize
:
import numpy as np from sklearn.preprocessing import normalize x = np.random.rand(1000)*10 norm1 = x / np.linalg.norm(x) norm2 = normalize(x[:,np.newaxis], axis=0).ravel() print np.all(norm1 == norm2) # True
回答2:
I would agree that it were nice if such a function was part of the included batteries. But it isn't, as far as I know. Here is a version for arbitrary axes, and giving optimal performance.
import numpy as np def normalized(a, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[l2==0] = 1 return a / np.expand_dims(l2, axis) A = np.random.randn(3,3,3) print(normalized(A,0)) print(normalized(A,1)) print(normalized(A,2)) print(normalized(np.arange(3)[:,None])) print(normalized(np.arange(3)))
回答3:
You can specify ord to get the L1 norm. To avoid zero division I use eps, but that's maybe not great.
def normalize(v): norm=np.linalg.norm(v, ord=1) if norm==0: norm=np.finfo(v.dtype).eps return v/norm
回答4:
There is also the function unit_vector()
to normalize vectors in the popular transformations module by Christoph Gohlke:
import transformations as tf import numpy as np data = np.array([[1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [1.0, 2.0, 3.0]]) print(tf.unit_vector(data, axis=1))