mean、sum、prod
import torch
a = torch.rand(2, 2)
print('a\n', a)
print('求平均\n', torch.mean(a))
print('求和\n', torch.sum(a))
print('求所有元素相乘\n', torch.prod(a))
输出结果:
a
tensor([[0.5561, 0.5030],
[0.6866, 0.5295]])
求平均
tensor(0.5688)
求和
tensor(2.2753)
求所有元素相乘
tensor(0.1017)
指定维度:mean、sum、prod、argmax、argmin、std、var、median、mode
a = torch.rand(2, 2)
print('指定维度')
print('a\n', a)
print('求每一列的平均值\n', torch.mean(a, dim=0))
print('求每一列的和\n', torch.sum(a, dim=0))
print('求每一列的所有元素相乘的积 \n', torch.prod(a, dim=0))
print('求每一列的最大值的索引值 \n', torch.argmax(a, dim=0))
print('求每一列的最小值的索引值 \n', torch.argmin(a, dim=0))
print('标准差\n', torch.std(a))
print('方差\n', torch.var(a))
print('中位数\n', torch.median(a))
print('众数 \n', torch.mode(a))
输出结果:
指定维度
a
tensor([[0.4456, 0.7302],
[0.1626, 0.7049]])
求每一列的平均值
tensor([0.3041, 0.7175])
求每一列的和
tensor([0.6081, 1.4351])
求每一列的所有元素相乘的积
tensor([0.0724, 0.5147])
求每一列的最大值的索引值
tensor([0, 0])
求每一列的最小值的索引值
tensor([1, 1])
标准差
tensor(0.2654)
方差
tensor(0.0704)
中位数
tensor(0.4456)
众数
torch.return_types.mode(
values=tensor([0.4456, 0.1626]),
indices=tensor([0, 0]))
直方图 histc
print('直方图')
a = torch.rand(2, 2)*10
print('a\n', a)
# 第二个参数为统计多少个区间 第三、四个参数的意思为取当前tensor
# 中的最大值和最小值作为统计的最大值和最小值的起始位置
print(torch.histc(a, 4, 0, 0))
# 输出的结果应该是每个a中的值在4个对应区间中的个数
输出结果:
直方图
a
tensor([[0.3696, 8.9111],
[2.2371, 4.2902]])
tensor([2., 1., 0., 1.])
bincount
import torch
# 第三个参数是多少维度
a = torch.randint(0, 10, [10])
print('a\n', a)
# 本例输出的结果就是统计0 出现多少次,1 出现多少次,2 出现多少次。。。。。。
# 分别是对应位置的统计次数,比如输出的列表中的第一个位置就是0出现了多少次
# 另外bincount只能处理一维的数据
print('统计出现多少次\n', torch.bincount(a))
输出结果:
a
tensor([1, 3, 4, 6, 6, 8, 4, 4, 1, 0])
统计出现多少次
tensor([1, 2, 0, 1, 3, 0, 2, 0, 1])