torch.stack()函数:
torch.stack(sequence, dim=0)
1.函数功能:
沿一个新维度对输入张量序列进行连接,序列中所有张量应为相同形状;stack 函数返回的结果会新增一个维度,而stack()函数指定的dim参数,就是新增维度的(下标)位置。
2.参数列表:
sequence:参与创建新张量的几个张量;
dim:新增维度的(下标)位置,当dim = -1时默认最后一个维度;
返回值:输出张量。
# 输入张量信息:
# a=[i][j]
# b=[i][j]
c = stack((a,b), dim=0)
# 输出张量信息:
# c[0][i][j] = a[i][j]
# c[1][i][j] = b[i][j]
3.应用举例:
1)
import torch
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
c = torch.stack([a, b], 0)
print(a)
print(b)
print(c)
# 输出信息:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tensor([[11, 22, 33],
[44, 55, 66],
[77, 88, 99]])
tensor([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[11, 22, 33],
[44, 55, 66],
[77, 88, 99]]])
2)
import torch
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
c = torch.stack([a, b], 1)
print(a)
print(b)
print(c)
# 输出信息:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tensor([[11, 22, 33],
[44, 55, 66],
[77, 88, 99]])
tensor([[[ 1, 2, 3],
[11, 22, 33]],
[[ 4, 5, 6],
[44, 55, 66]],
[[ 7, 8, 9],
[77, 88, 99]]])
3)
import torch
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = torch.tensor([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
c = torch.stack([a, b], 2)
print(a)
print(b)
print(c)
# 输出信息:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
tensor([[11, 22, 33],
[44, 55, 66],
[77, 88, 99]])
tensor([[[ 1, 11],
[ 2, 22],
[ 3, 33]],
[[ 4, 44],
[ 5, 55],
[ 6, 66]],
[[ 7, 77],
[ 8, 88],
[ 9, 99]]])
4)
import torch
a = torch.tensor([[[1, 2, 3], [4, 5, 6], [7, 8, 9]],[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
b = torch.tensor([[[11, 22, 33], [44, 55, 66], [77, 88, 99]], [[11, 22, 33], [44, 55, 66], [77, 88, 99]]])
c = torch.stack([a, b], 3)
print(a)
print(b)
print(c)
# 输出信息:
tensor([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]])
tensor([[[11, 22, 33],
[44, 55, 66],
[77, 88, 99]],
[[11, 22, 33],
[44, 55, 66],
[77, 88, 99]]])
tensor([[[[ 1, 11],
[ 2, 22],
[ 3, 33]],
[[ 4, 44],
[ 5, 55],
[ 6, 66]],
[[ 7, 77],
[ 8, 88],
[ 9, 99]]],
[[[ 1, 11],
[ 2, 22],
[ 3, 33]],
[[ 4, 44],
[ 5, 55],
[ 6, 66]],
[[ 7, 77],
[ 8, 88],
[ 9, 99]]]])