torch.mean

mean()函數的參數:dim=0,按行求平均值,返回的形狀是(1,列數);dim=1,按列求平均值,返回的形狀是(行數,1),默認不設置dim的時候,返回的是所有元素的平均值。

x=torch.arange(12).view(4,3)
'''
注意:在這裏使用的時候轉一下類型,否則會報RuntimeError: Can only calculate the mean of floating types. Got Long instead.的錯誤。
查看了一下x元素類型是torch.int64,根據提示添加一句x=x.float()轉爲tensor.float32就行
'''
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:')
print(x)
print('x_mean0:')
print(x_mean0)
print('x_mean1:')
print(x_mean1)
print('x_mean:')
print(x_mean)

查看了一下x元素類型是torch.int64,根據提示添加一句x=x.float()轉爲tensor.float32就行
輸出結果:

x:
tensor([[ 0.,  1.,  2.],
        [ 3.,  4.,  5.],
        [ 6.,  7.,  8.],
        [ 9., 10., 11.]])
x_mean0:
tensor([[4.5000, 5.5000, 6.5000]])
x_mean1:
tensor([[ 1.],
        [ 4.],
        [ 7.],
        [10.]])
x_mean:
tensor(5.5000)

torch.mean().mean()

x=torch.arange(24).view(4,3,2)
x=x.float()
x_mean=torch.mean(x)
print(x)
print(x.mean())
print(x.mean(dim=0,keepdim=True).mean(dim=1,keepdim=True).mean(dim=2,keepdim=True))
print(x.mean(dim=1,keepdim=True).mean(dim=2,keepdim=True))

輸出:

tensor([[[ 0.,  1.],
         [ 2.,  3.],
         [ 4.,  5.]],

        [[ 6.,  7.],
         [ 8.,  9.],
         [10., 11.]],

        [[12., 13.],
         [14., 15.],
         [16., 17.]],

        [[18., 19.],
         [20., 21.],
         [22., 23.]]])
tensor(11.5000)
tensor([[[11.5000]]])
tensor([[[ 2.5000]],

        [[ 8.5000]],

        [[14.5000]],

        [[20.5000]]])

torch.mean()和torch.mean(dim=0).mean(dim=1)的區別

以二維爲例:torch.mean()返回的是一個標量,而torch.mean(dim=0).mean(dim=1)返回的是一個1行1列的張量,雖然數值相同

x=torch.arange(12).view(4,3)
x=x.float()
x_mean=torch.mean(x)
print(x_mean)
y= x.mean(dim=0, keepdim=True).mean(dim=1, keepdim=True)
print(y)

輸出:

tensor(5.5000)
tensor([[5.5000]])

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章