Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy求和结果及其转置给出了相同的答案_Python_Numpy - Fatal编程技术网

Python numpy求和结果及其转置给出了相同的答案

Python numpy求和结果及其转置给出了相同的答案,python,numpy,Python,Numpy,我很难理解如何以正确的方式做这件事 print np.sum(X,axis=1) 及 给我同样的结果。 最好的解决方法是什么 为什么这样的事情不应该被视为numpy中的bug 例如:X=[[1,2],[3,4]] 对于第一个结果,我希望得到数组[[3,7]],第二个结果是数组[[3],[7]]。也可以是相反的方式..其实并不重要。我想你应该先转置: print np.sum(X.T,axis=1) 求和后得到的是一个平面数组,因此很明显,在变换1d数组时,会得到与原始数组相同的输出 In [

我很难理解如何以正确的方式做这件事

print np.sum(X,axis=1)

给我同样的结果。 最好的解决方法是什么

为什么这样的事情不应该被视为numpy中的bug

例如:X=[[1,2],[3,4]]


对于第一个结果,我希望得到数组[[3,7]],第二个结果是数组[[3],[7]]。也可以是相反的方式..其实并不重要。

我想你应该先转置:

print np.sum(X.T,axis=1)
求和后得到的是一个平面数组,因此很明显,在变换1d数组时,会得到与原始数组相同的输出

In [14]: X=np.array([[1,2,3],[4,5,6]])    
In [15]: np.sum(X, axis=1)
Out[15]: array([ 6, 15])    
In [16]: np.sum(X, axis=1).T
Out[16]: array([ 6, 15])    
In [17]: np.sum(X.T, axis=1)
Out[17]: array([5, 7, 9])

如果它在错误的轴上求和,为什么不改变它呢

>> np.sum(np.array([[1, 2, 3], [2, 3, 4]]), axis=1)
array([6, 9])

>> np.sum(np.array([[1, 2, 3], [2, 3, 4]]), axis=0)
array([3, 5, 7])
编辑

您可以重塑生成的阵列,如下所示:

>> np.sum(np.array([[1, 2, 3], [2, 3, 4]]), axis=1).reshape((2, 1))
array([[6],
    [9]])

如果要在计算总和后保留额外的单例维度,可以将keepdims=True传递给sum:

除了使用keepdims外,您还可以重塑输出以插入新轴,以替换在减速过程中丢失的轴,例如:

# the '-1' here means that numpy will infer the size in the first dimension to
# match the number of elements in the result array
print(np.sum(X, axis=1).reshape(-1, 1).shape)
# (2, 1)

print(np.sum(X, axis=1)[:, np.newaxis].shape)
# (2, 1)

# indexing with 'None' is equivalent to 'np.newaxis'
print(np.sum(X, axis=1)[:, None].shape)
# (2, 1)

没问题。顺便说一句,改变轴不是更好吗?不,我想在第一个结果中使用数组[[6,5]],并使用数组[[6],[5]]。达到这一结果的最佳方式是什么?我用它来进行矩阵乘法,我需要T矩阵。@AmiTavory,确实是这样,我只是想向OP展示他们得到的正是他们应该得到的。@member555,我不确定我是否明白,请将您的输入添加到您的问题中,并期望output@PadraicCunningham我很确定他指的是6,15。不,我想要数组[[6,5]]在第一个结果和数组[[6],[5]]中。达到这一结果的最佳方式是什么?我使用它进行矩阵乘法,我需要T matrixit对每个输入数组进行整形2,1?这意味着2行,1列-行数取决于您的输入矩阵。@member555,不是对每个输入,使用原始数组的形状sum的默认操作是将维数减少1,在这种情况下,从2d减少到1d。1d的转置就是它本身。
X = np.array([[1, 2, 3], [2, 3, 4]])

print(np.sum(X, axis=0).shape)
# (3,)

print(np.sum(X, axis=0, keepdims=1).shape)
# (1, 3)

print(np.sum(X, axis=1, keepdims=1).shape)
# (2, 1)
# the '-1' here means that numpy will infer the size in the first dimension to
# match the number of elements in the result array
print(np.sum(X, axis=1).reshape(-1, 1).shape)
# (2, 1)

print(np.sum(X, axis=1)[:, np.newaxis].shape)
# (2, 1)

# indexing with 'None' is equivalent to 'np.newaxis'
print(np.sum(X, axis=1)[:, None].shape)
# (2, 1)