How to normalize an array in NumPy?

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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)) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!