# Pytorch torch.mean() 平均值的簡單用法

Pytorch torch.mean()的簡單用法

```import torch

x1 = torch.Tensor([1, 2, 3, 4])
x2 = torch.Tensor([[1],
[2],
[3],
[4]])
x3 = torch.Tensor([[1, 2],
[3, 4]])
y1 = torch.mean(x1)
y2 = torch.mean(x2)
y3 = torch.mean(x3)
print(y1)
print(y2)
print(y3)```

tensor(2.5000)
tensor(2.5000)
tensor(2.5000)

```import torch

x = torch.Tensor([1, 2, 3, 4, 5, 6]).view(2, 3)
y_0 = torch.mean(x, dim=0) ##  每列求均值
y_1 = torch.mean(x, dim=1) ###  每行求均值
print(x)
print(y_0)
print(y_1)```

tensor([[1., 2., 3.],
[4., 5., 6.]])
tensor([2.5000, 3.5000, 4.5000])
tensor([2., 5.])

y = torch.mean(x, dim=1, keepdim=True)

```import torch
import numpy as np

# ======初始化一個三維矩陣=====
A = torch.ones((4,3,2))

# ======替換三維矩陣裏面的值======
A[0] = torch.ones((3,2)) *1
A[1] = torch.ones((3,2)) *2
A[2] = torch.ones((3,2)) *3
A[3] = torch.ones((3,2)) *4

print(A)

B = torch.mean(A ,dim=0)
print(B)

B = torch.mean(A ,dim=1)
print(B)

B = torch.mean(A ,dim=2)
print(B)```

```tensor([[[1., 1.],
[1., 1.],
[1., 1.]],

[[2., 2.],
[2., 2.],
[2., 2.]],

[[3., 3.],
[3., 3.],
[3., 3.]],

[[4., 4.],
[4., 4.],
[4., 4.]]])
tensor([[2.5000, 2.5000],
[2.5000, 2.5000],
[2.5000, 2.5000]])
tensor([[1., 1.],
[2., 2.],
[3., 3.],
[4., 4.]])
tensor([[1., 1., 1.],
[2., 2., 2.],
[3., 3., 3.],
[4., 4., 4.]])```

REF

https://blog.csdn.net/qq_40714949/article/details/115485140