py
复制代码
import torch
# 创建一个三维张量
x = torch.tensor([
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]
])
print("Original tensor x:")
print(x)
print(x.shape)
>>> tensor([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
torch.Size([2, 2, 3])
# 沿第0维求和
sum_dim0 = torch.sum(x, dim=0)
print("Sum along dimension 0:")
print(sum_dim0)
print()
>>>Sum along dimension 0:
tensor([[ 8, 10, 12],
[14, 16, 18]])
# 沿第1维求和
sum_dim1 = torch.sum(x, dim=1)
print("Sum along dimension 1:")
print(sum_dim1)
print()
>>>Sum along dimension 1:
tensor([[ 5, 7, 9],
[17, 19, 21]])
# 沿第2维求和
sum_dim2 = torch.sum(x, dim=2)
print("Sum along dimension 2:")
print(sum_dim2)
print()
>>>Sum along dimension 2:
tensor([[ 6, 15],
[24, 33]])
sum_dim3 = torch.sum(x, dim=(1,2))
print("Sum along dimension (1,2):")
print(sum_dim3)
print()
>>>Sum along dimension (1,2):
tensor([21, 57])
sum_dim4 = torch.sum(x, dim=(0,1))
print("Sum along dimension (0,1):")
print(sum_dim4)
print()
>>>Sum along dimension (0,1):
tensor([22, 26, 30])