当我使用np.stack时,有时必须使用axis,就像axis = 1。我不明白轴的意义。例如,
c1 = np.ones((2, 3))
c2 = np.zeros((2, 3))
c = np.stack([c1, c2], axis = 1)
这显示了,
array([[[1., 1., 1.],
[0., 0., 0.]],
[[1., 1., 1.],
[0., 0., 0.]]])
结果是什么规则?
答案 0 :(得分:0)
轴表示尺寸。举一个简单的例子,考虑numpy.sum
import numpy as np
a=np.array([1,2,3],[2,3,1])
sum1=np.sum(a,axis=0)
sum2=np.sum(a,axis=1)
print sum1,sum2
这将给我sum1 = 12和sum2 = [3,5,4]
我的数组有两个维度/轴。第一个长度为2,第二个长度为3.因此,通过指定轴,您可以简单地告诉您的代码您希望在哪个维度上完成工作。
numpy.ndarray.ndim可以告诉你有多少轴
答案 1 :(得分:0)
实际上sum1给出(3,5,4),sum2给出(6,6) 但是你的评论让我了解了轴在Numpy中是如何工作的。谢谢。 据我所知,axis = 0表示它将沿列添加,axis = 1表示它将沿行添加。
答案 2 :(得分:0)
In your example, the arrays are 2d, and axis
normally refers to one of those 2 dimensions.
In [441]: c1
Out[441]:
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
In [442]: c1.sum(axis=0)
Out[442]: array([ 2., 2., 2.])
In [443]: c1.sum(axis=1)
Out[443]: array([ 3., 3.])
Exactly what a function does with the axis
parameter is up to the function itself. In the sum
case is adds 'along' that axis, and returns a value that is 'missing' that axis. It's easier to see that action than it is to describe it.
The role of axis
in concatenate
is illustrated by:
In [452]: np.concatenate((c1,c2),axis=0).shape
Out[452]: (4, 3)
In [453]: np.concatenate((c1,c2),axis=1).shape
Out[453]: (2, 6)
stack
adds a dimension. It's a relatively new API to concatenate
, and works by first adding a dimension to each input array
In [448]: np.stack((c1,c2,c1,c2),axis=0).shape
Out[448]: (4, 2, 3)
In [449]: np.stack((c1,c2,c1,c2),axis=1).shape
Out[449]: (2, 4, 3)
In [450]: np.stack((c1,c2,c1,c2),axis=2).shape
Out[450]: (2, 3, 4)