NumPy: how to quickly normalize many vectors?

前端 未结 6 975
梦毁少年i
梦毁少年i 2021-01-31 04:47

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         


        
6条回答
  •  温柔的废话
    2021-01-31 05:47

    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
    

    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
    

提交回复
热议问题