NumPy:如何快速归一化许多向量? [英] NumPy: how to quickly normalize many vectors?
问题描述
如何在NumPy中对向量列表进行优雅的标准化?
How can a list of vectors be elegantly normalized, in NumPy?
这是一个不起作用的示例:
Here is an example that does not work:
from numpy import *
vectors = array([arange(10), arange(10)]) # All x's, then all y's
norms = apply_along_axis(linalg.norm, 0, vectors)
# Now, what I was expecting would work:
print vectors.T / norms # vectors.T has 10 elements, as does norms, but this does not work
最后一个操作会产生形状不匹配:对象无法广播为单个形状".
The last operation yields "shape mismatch: objects cannot be broadcast to a single shape".
如何使用NumPy优雅地完成vectors
中2D向量的归一化?
How can the normalization of the 2D vectors in vectors
be elegantly done, with NumPy?
编辑:为什么在向norms
添加尺寸时上述方法不起作用(根据我在下面的回答)?
Edit: Why does the above not work while adding a dimension to norms
does work (as per my answer below)?
推荐答案
好吧,除非我错过了什么,否则确实可以:
Well, unless I missed something, this does work:
vectors / norms
您的建议中的问题是广播规则.
The problem in your suggestion is the broadcasting rules.
vectors # shape 2, 10
norms # shape 10
形状不一样长!因此,规则是先在左侧上将小形状扩展一个:
The shape do not have the same length! So the rule is to first extend the small shape by one on the left:
norms # shape 1,10
您可以通过以下方式手动进行操作:
You can do that manually by calling:
vectors / norms.reshape(1,-1) # same as vectors/norms
如果要计算vectors.T/norms
,则必须手动进行重塑,如下所示:
If you wanted to compute vectors.T/norms
, you would have to do the reshaping manually, as follows:
vectors.T / norms.reshape(-1,1) # this works
这篇关于NumPy:如何快速归一化许多向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!