1 torch.mean(input, dim, keepdim = False)
1.1 参数介绍
input: 输入的tensor, 注意输入只能是tensor , 否则会报错
dim: 计算平均值的维度, dim = 0 表示按列求平均, dim = 1 表示按行求平均, dim 不设置, 则表示对所有数求平均
keepdim: 默认为 False, 表示是否和输入张量为一个维度, 若 keepdim = Flase, 则输出为一维张量
2 程序示例
2.1 数据不为 float 报错
import torch
a = torch.tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
print(a)
print('dim = 0:\t',torch.mean(a, dim = 0))
>>mean(): could not infer output dtype. Input dtype must be either a floating point or complex dtype. Got: Long
修改:
import torch
a = torch.tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype = float)
2.2 dim = 0, 1, 默认, keepdim = False
import torch
a = torch.tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype = float)
print(a)
print('dim = 0:\t',torch.mean(a, dim = 0))
print('dim = 1:\t',torch.mean(a, dim = 1))
print('dim = 1:\t',torch.mean(a))
>>tensor([[1., 1., 1.],
[2., 2., 2.],
[3., 3., 3.]], dtype=torch.float64)
>>dim = 0: tensor([2., 2., 2.], dtype=torch.float64)
>>dim = 1: tensor([1., 2., 3.], dtype=torch.float64)
>>dim = 1: tensor(2., dtype=torch.float64)
可以看出, dim 不设置维度, 输出为一个数值张量, 若设置维度 dim, 则输出为一个一维张量
2.3 dim = 1, 2, keepdim = True
import torch
a = torch.tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype = float)
print(a)
print('dim = 0:\t',torch.mean(a, dim = 0, keepdim = True))
print('dim = 1:\t',torch.mean(a, dim = 1, keepdim = True))
>>tensor([[1., 1., 1.],
[2., 2., 2.],
[3., 3., 3.]], dtype=torch.float64)
>>dim = 0: tensor([[2., 2., 2.]], dtype=torch.float64)
>>dim = 1: tensor([[1.],
[2.],
[3.]], dtype=torch.float64)