基础规则
每一维用形式: start:end:stride
切割,不同维用逗号隔开。其中:
- strart不填默认为0
- stride不填默认为1
- end不填默认为最后一项
- 取该维全部用一个冒号
- 不包括end
特点:这种切片不会改变秩,即不会改变 len(shape)
但是会改变shape的具体数值。
示例:
>>> probs = np.array([[(1.1,1.2,1.3,1.4), (2.1,2.2,2.3,2.4)],[(3.1,3.2,3.3,3.4), (4.1,4.2,4.3,4.4)]])
>>> probs
array([[[1.1, 1.2, 1.3, 1.4],
[2.1, 2.2, 2.3, 2.4]],
[[3.1, 3.2, 3.3, 3.4],
[4.1, 4.2, 4.3, 4.4]]])
>>> probs.shape
(2, 2, 4)
start、stride、end都齐全的时候,切片包括start 不包括end ,如下:
>>> a = probs[:,:,0:4:2]
>>> a
array([[[1.1, 1.3],
[2.1, 2.3]],
[[3.1, 3.3],
[4.1, 4.3]]])
>>> a.shape
(2, 2, 2)
stride缺省的时候默认为1:
>>> b = probs[:,:,0:2]
>>> b
array([[[1.1, 1.2],
[2.1, 2.2]],
[[3.1, 3.2],
[4.1, 4.2]]])
>>> b.shape
(2, 2, 2)
start缺省的时候默认为0
也就是 b = probs[:,:,0:2]
和 c = probs[:,:,:2]
结果是一样的:
>>> c = probs[:,:,:2]
>>> c
array([[[1.1, 1.2],
[2.1, 2.2]],
[[3.1, 3.2],
[4.1, 4.2]]])
>>> c.shape
(2, 2, 2)
但是,c = probs[:,:,:2]
和 d = probs[:,:,::2]
可不一样!后者表示步长为2:
>>> d = probs[:,:,::2]
>>> d
array([[[1.1, 1.3],
[2.1, 2.3]],
[[3.1, 3.3],
[4.1, 4.3]]])
>>> d.shape
(2, 2, 2)
省略冒号,直接填数字的情况
特点:这种情况会改变秩(即 len(shape)
)
切 dim=2
这一维:
>>> e_0 = probs[:,:,0]
>>> e_0
array([[1.1, 2.1],
[3.1, 4.1]])
>>> e_0.shape
(2, 2)
>>> e_2 = probs[:,:,2]
>>> e_2
array([[1.3, 2.3],
[3.3, 4.3]])
>>> e_2.shape
(2, 2)
切 dim=1
这一维:
f_0 = probs[:,0,:]
>>> f_0
array([[1.1, 1.2, 1.3, 1.4],
[3.1, 3.2, 3.3, 3.4]])
>>> f_0.shape
(2, 4)
>>> f_1 = probs[:,1,:]
>>> f_1
array([[2.1, 2.2, 2.3, 2.4],
[4.1, 4.2, 4.3, 4.4]])
>>> f_1.shape
(2, 4)
切 dim=0
这一维:
>>> g = probs[0,:,:]
>>> g
array([[1.1, 1.2, 1.3, 1.4],
[2.1, 2.2, 2.3, 2.4]])
>>> g.shape
(2, 4)
切割维度 ≠ 张量或数组维度时
维数不相等时,省略的维数默认全切,即默认 :
示例:
h = probs[:,0]
等于 f = probs[:,0,:]
>>> h = probs[:,0]
>>> h
array([[1.1, 1.2, 1.3, 1.4],
[3.1, 3.2, 3.3, 3.4]])
>>> h.shape
(2, 4)
i = probs[0]
等于 g = probs[0,:,:]
>>> i = probs[0]
>>> i
array([[1.1, 1.2, 1.3, 1.4],
[2.1, 2.2, 2.3, 2.4]])
>>> i.shape
(2, 4)