YDOOK:Pytorch教程:tensor 张量内各个元素之和 相加值输出
© YDOOK Jinwei Lin, shiye.work
import torch
import numpy as np
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(t1)
# 将张量 t1 的各个值相加
print(t1.sum())
# 输出
print(type(t1.sum()))
# 使用 .item()
# 传化为Python变量输出和
print(t1.sum().item())
outcome:
tensor([[1, 2, 3],
[4, 5, 6]])
tensor(21)
<class 'torch.Tensor'>
21
Process finished with exit code 0