- max()
参数: dim=0,返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引) dim=1,返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)
示例:
import torch
a = torch.randn(3,3)
print(a)
print(torch.max(a,0))
print(torch.max(a,1))
----------------------------
tensor([[-0.9620, -0.2919, -0.4747],
[ 0.2217, 0.5707, 0.8449],
[-1.3816, 0.5385, 0.1624]])
torch.return_types.max(
values=tensor([0.2217, 0.5707, 0.8449]),
indices=tensor([1, 1, 1]))
torch.return_types.max(
values=tensor([-0.2919, 0.8449, 0.5385]),
indices=tensor([1, 2, 1]))
Process finished with exit code 0
- mean()
参数: dim=0,按行求平均值,返回的形状是(1,列数); dim=1,按列求平均值,返回的形状是(行数,1); 默认不设置dim的时候,返回的是所有元素的平均值。
示例:
import torch
x=torch.arange(12).view(4,3)
x=x.float()
x_mean=torch.mean(x)
x_mean0=torch.mean(x,dim=0,keepdim=True)
x_mean1=torch.mean(x,dim=1,keepdim=True)
print('x:', x)
print('x_mean:', x_mean)
print('x_mean0:', x_mean0)
print('x_mean1:', x_mean1)
-------------------------------
x: tensor([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]])
x_mean: tensor(5.5000)
x_mean0: tensor([[4.5000, 5.5000, 6.5000]])
x_mean1: tensor([[ 1.],
[ 4.],
[ 7.],
[10.]])
Process finished with exit code 0
- torch.mean() VS torch.mean().mean()
(以二维为例)torch.mean()返回的是一个标量,而torch.mean(dim=0).mean(dim=1)返回的是一个1行1列的张量,虽然数值相同
|