简体   繁体   English

numpy中多个向量的元素最小值

[英]Element-wise minimum of multiple vectors in numpy

I know that in numpy I can compute the element-wise minimum of two vectors with 我知道在numpy中我可以计算出两个向量的元素最小值

numpy.minimum(v1, v2)

What if I have a list of vectors of equal dimension, V = [v1, v2, v3, v4] (but a list, not an array)? 如果我有一个相等维度的向量列表, V = [v1, v2, v3, v4] (但列表,而不是数组),该怎么办? Taking numpy.minimum(*V) doesn't work. numpy.minimum(*V)不起作用。 What's the preferred thing to do instead? 相反,首选的是什么?

*V works if V has only 2 arrays. *V如果V只有2个数组,则V np.minimum is a ufunc and takes 2 arguments. np.minimumufunc和需要两个参数。

As a ufunc it has a .reduce method, so it can apply repeated to a list inputs. 作为一个ufunc它有一个.reduce方法,因此它可以重复应用于列表输入。

In [321]: np.minimum.reduce([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
Out[321]: array([ 0.,  1.,  0.])

I suspect the np.min approach is faster, but that could depend on the array and list size. 我怀疑np.min方法更快,但这可能取决于数组和列表大小。

In [323]: np.array([np.arange(3), np.arange(2,-1,-1), np.ones((3,))]).min(axis=0)
Out[323]: array([ 0.,  1.,  0.])

The ufunc also has an accumulate which can show us the results of each stage of the reduction. ufunc还有一个accumulate ,它可以向我们显示减少的每个阶段的结果。 Here's it's not to interesting, but I could tweak the inputs to change that. 这不是有趣的,但我可以调整输入来改变它。

In [325]: np.minimum.accumulate([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
     ...: 
Out[325]: 
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.]])

Convert to NumPy array and perform ndarray.min along the first axis - 转换为NumPy数组并沿第一轴执行ndarray.min -

np.asarray(V).min(0)

Or simply use np.amin as under the hoods, it will convert the input to an array before finding the minimum along that axis - 或者只是在np.amin下使用np.amin ,它会在沿着该轴找到最小值之前将输入转换为数组 -

np.amin(V,axis=0)

Sample run - 样品运行 -

In [52]: v1 = [2,5]

In [53]: v2 = [4,5]

In [54]: v3 = [4,4]

In [55]: v4 = [1,4]

In [56]: V = [v1, v2, v3, v4]

In [57]: np.asarray(V).min(0)
Out[57]: array([1, 4])

In [58]: np.amin(V,axis=0)
Out[58]: array([1, 4])

If you need to final output as a list, append the output with .tolist() . 如果需要将最终输出作为列表,请使用.tolist()附加输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM