torch.mean()

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)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值