Tensor常用的高端切片—T[…,:n]和T[:,n]的区别
1. 先说结论
结论一:
T[ ... , : n ]
取
最后1维
的前n个元素
结论二:
T[ : , :n ]
取
第2维
的前n个元素
结论二扩展:
T[
:,:,
:n]取
第3维
的前n个元素,T[
:,:,:,
:n]取
第4维
的前n个元素前边有几个
:,
就相当于前边几个完整(省略)的维度。
2. 代码与分析
np.array( )
和
terch.tensor( )
和
tf.tensor( )
切片效果一样,这里以np.array()进行演示。
2.1 […,:2]和[:,:2]之间的区别
import numpy as np
anchors = np.array( [
[[1,2,3], [4,5,6], [7,8,9]],
[[10,20,30], [40,50,60], [70,80,90]],
[[100,200,300], [400,500,600], [700,800,900]]
])
print(anchors.shape) # (3,3,3) : 3行,每横分3段,每段3个数字。
c = anchors[...,:2] # 最后一维,每三个数字取前2个数字
print('C:',c)
print(c.shape)
d = anchors[:,:2] # 第二维,3段取前2段
print('D:',d)
print(d.shape)
c的打印结果 | d的打印结果 |
---|---|
![]() |
![]() |
2.2 [:,:2]和[:,:,:2]之间的区别
import numpy as np
anchors = np.array([
[
[[1,2,3], [4,5,6], [7,8,9]],
[[10,20,30], [40,50,60], [70,80,90]],
[[100,200,300], [400,500,600], [700,800,900]]
], [
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[10, 20, 30], [40, 50, 60], [70, 80, 90]],
[[100, 200, 300], [400, 500, 600], [700, 800, 900]]
]
])
print(anchors.shape) # (2, 3, 3, 2) : 2块,每块3行,每行3段,每段3个数字
d = anchors[:,:2] # :块,3行中的前2行
print('D:',d)
print(d.shape)
f = anchors[:,:,:2] # :块,:行,3段中的前两段
print('F:',f)
print(f.shape)
d的打印结果 | f的打印结果 |
---|---|
![]() |
![]() |
3. 总结
一个tensor如果只有
2维
,那么tensor[…,:n]和tensor[:,:n]
结果
是
一样
的。
如果这个tensor是一个多维度张量,如果想取
最后 一维
的前n个元素则选用
...
(常用),如果想取
中间某维度
的前几个则用
:
。