目录
1.torch.stack()的官方解释
1.1英文原版
Concatenates a sequence of tensors along a new dimension.
All tensors need to be of the same size.
Parameters:
tensors (sequence of Tensors) – sequence of tensors to concatenate
dim (int) – dimension to insert. Has to be between 0 and the number of dimensions of concatenated tensors (inclusive)
Keyword Arguments:
out (Tensor, optional) – the output tensor.
1.2中文解释
1.2.1沿新维度连接一系列张量。
1.2.2所有张量的大小必须相同。
1.2.3参数:
-
张量(张量序列) – 要连接的张量序列
-
维度(整数) – 要插入的尺寸。必须介于 0 和数字之间 级联张量的维数(包括)
1.3使用
outputs = torch.stack(inputs, dim) → Tensor
-
inputs : 待连接的张量序列。
注:python
的序列数据只有list
和tuple
。 -
dim : 新的维度, 必须在
0
到len(outputs)
之间。
注:len(outputs)
是生成数据的维度大小,也就是outputs
的维度值。
即可以将多个低纬张量拼凑为一个高维张量。
2.代码应用
用来实现一个计算多个通道的输出。
def corr2d_multi_in_out(X, K):
# 迭代“K”的第0个维度,每次都对输入“X”执行互相关运算。
# 最后将所有结果都叠加在一起
return torch.stack([corr2d_multi_in(X, k) for k in K], 0)
X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])
通过将核张量K
与K+1
(K
中每个元素加1)和K+2
连接起来,构造了一个具有3个输出通道的卷积核。
K = torch.stack((K, K + 1, K + 2), 0)
K.shape