Python Numpy 元素明智的划分没有按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24585661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Numpy element wise division not working as expected
提问by yayu
From the docs, here is how element division works normally
从文档中,这是元素划分的正常工作方式
a1 = np.array([8,12,14])
b1 = np.array([4,6,7])
a1/b1
array([2, 2, 2])
Which works. I am trying the same thing, I think, on different arrays and it doesn't. For two 3-dim vectors it is returning a 3x3 matrix. I even made sure their "shape is same" but no difference.
哪个有效。我想在不同的阵列上尝试同样的事情,但事实并非如此。对于两个 3-dim 向量,它返回一个 3x3 矩阵。我什至确保它们的“形状相同”但没有区别。
>> t
array([[ 3.17021277e+00],
[ 4.45795858e-15],
[ 7.52842809e-01]])
>> s
array([ 1.00000000e+00, 7.86202619e+02, 7.52842809e-01])
>> t/s
array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00],
[ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15],
[ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]])
t/s.T
array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00],
[ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15],
[ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]])
采纳答案by Magellan88
This is because the shapes of your two arrays are t.shape = (3,1) and s.shape=(3,). So the broadcasting rules apply: They state that if the two dimensions are equal, then do it element-wise, if they are not the same it will fail unless one of them is one, an this is where it becomes interesting: In this case the array with the dimension of one will iterate the operation over all elements of the other dimension.
这是因为你的两个数组的形状是 t.shape = (3,1) 和 s.shape=(3,)。因此广播规则适用:他们指出,如果两个维度相等,则按元素进行操作,如果它们不相同,它将失败,除非其中之一是一个,这就是它变得有趣的地方:在这种情况下维度为一的数组将对另一维度的所有元素进行迭代。
I guess what you want to do would be
我想你想做的是
t[:,0] / s
or
或者
np.squeeze(t) / s
Both of which will get rid of the empty first dimension in t. This really is not a bug it is a feature! because if you have two vectors and you want to do an operation between all elements you do exactly that:
两者都将摆脱 t 中空的第一维。这真的不是一个错误,而是一个功能!因为如果你有两个向量并且你想在所有元素之间做一个操作,你就这样做:
a = np.arange(3)
b = np.arange(3)
element-wise you can do now:
元素明智你现在可以做:
a*b = [0,1,4]
If you would want to do have this operation performed between all elements you can insert these dimensions of size one like so:
如果您希望在所有元素之间执行此操作,您可以插入这些尺寸为 1 的尺寸,如下所示:
a[np.newaxis,:] * b[:,np.newaxis]
Try it out! It really is a convenient concept, although I do see how this is confusing at first.
试试看!这确实是一个方便的概念,尽管一开始我确实看到这是多么令人困惑。