简体   繁体   English

numpy:将垂直数组除以其自身元素之一时出现意外结果

[英]numpy: unexpected result when dividing a vertical array by one of its own elements

So, I created an vertical numpy array, used the /= operator and the output seems to be incorrect. 所以,我创建了一个垂直的numpy数组,使用了/ =运算符,输出似乎不正确。 Basically if x is a vector, sa scalar. 基本上,如果x是向量,则为标量。 I would expect x /= s have every entry of x divided by s. 我希望x / = s的每个条目x除以s。 However, I couldn't make much sense of the output. 但是,我无法理解输出。 The operator is only applied on part of the entries in x, and I am not sure how they are chosen. 运算符仅适用于x中的部分条目,我不确定如何选择它们。

In [8]: np.__version__
Out[8]: '1.10.4'

In [9]: x = np.random.rand(5,1)

In [10]: x
Out[10]:
array([[ 0.47577008],
       [ 0.66127875],
       [ 0.49337183],
       [ 0.47195985],
       [ 0.82384023]])   ####

In [11]: x /= x[2]

In [12]: x
Out[12]:
array([[ 0.96432356],
       [ 1.3403253 ],
       [ 1.        ],
       [ 0.95660073],
       [ 0.82384023]])   #### this entry is not changed.

Your value of x[2] changes to 1 midway through the evaluation. 在评估过程中,x [2]的值变为1。 you need to make a copy of the value then divide each element by it, either assign it to another variable or use copy ie 你需要制作一个值的副本,然后将每个元素除以它,或者将它分配给另一个变量或使用副本即

from copy import copy
x /= copy(x[2])

To understand why we need to do this lets look under the hood of what is happening. 要了解我们为什么需要这样做,让我们深入了解正在发生的事情。

In [9]: x = np.random.rand(5,1)

Here we define x as an array, but what isn't exactly clear that each element in this array is technically an array also. 这里我们将x定义为一个数组,但是不清楚这个数组中的每个元素在技术上也是一个数组。 This is the important distinction, as we are not dealing with defined values rather numpy array objects so in the next line: 这是一个重要的区别,因为我们不是处理定义的值而是处理numpy数组对象,所以在下一行:

In [11]: x /= x[2]

We end up essentially 'looking up' the value in x[2] which returns an array with one value, but because we're looking this up each time it is possible to change. 我们最终基本上“查找”x [2]中的值,该值返回一个具有一个值的数组,但因为我们每次都可以更改时查找它。

A cleaner solution would be to flatten the array into 1d therefore x[2] with now equal 0.49337183 instead of array( [0.49337183]) 一个更清洁的解决方案是将数组展平为1d,因此x [2]现在等于0.49337183而不是数组([0.49337183])

So before we do x /= x[2] we can call x = x.flatten() 所以在我们做x /= x[2]我们可以调用x = x.flatten()

Or better yet keep it 1d from the start x = np.random.rand(5) 或者更好的是从头开始保持1d x = np.random.rand(5)

And as for the reason x[3] changes and x[4] does not, the only real helpful answer I can give is that the division does not happen in order, complex buffering timey wimey stuff. 至于x [3]的变化和x [4]没有的原因,我能给出的唯一真正有用的答案是分裂不是按顺序发生的,复杂的缓冲时间很长的wimey东西。

理论上它只适用于奇数大小的矢量,但如果你这样做: x = np.random.rand(5,1) a = x[2]*1 x/=a它将起作用

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

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