如何在PyTorch中測量平均絕對誤差(MAE)?


平均絕對誤差計算的是輸入值和目標值(預測值和實際值)之間絕對差之和的平均值。為了在PyTorch中計算平均絕對誤差,我們使用torch.nn模組提供的L1Loss()函式。它建立一個度量平均絕對誤差的標準。

實際值和預測值都是具有相同元素數量的torch張量。這兩個張量可以具有任意數量的維度。此函式返回一個標量值的張量。它是torch.nn模組提供的損失函式的一種型別。損失函式用於透過最小化損失來最佳化深度神經網路。

語法

torch.nn.L1Loss()

步驟

要測量平均絕對誤差,可以按照以下步驟操作:

  • 匯入所需的庫。在以下所有示例中,所需的Python庫是torch。確保您已安裝它。

import torch
  • 建立輸入和目標張量並列印它們。

input = torch.randn(3, 4)
target = torch.randn(3, 4)
  • 建立一個標準來測量平均絕對誤差。

mae = nn.L1Loss()
  • 計算平均絕對誤差(損失)並列印它。

output = mae(input, target)
print("MAE loss:", output)

示例1

在此Python程式碼中,我們計算2維輸入和目標張量之間的平均絕對誤差損失。

# Import the required libraries
import torch
import torch.nn as nn

# define the input and target tensors
input = torch.randn(3, 4)
target = torch.randn(3, 4)

# print input and target tensors
print("Input Tensor:
", input) print("Target Tensor:
", target) # create a criterion to measure the mean absolute error mae = nn.L1Loss() # compute the loss (mean absolute error) output = mae(input, target) # output.backward() print("MAE loss:", output)

輸出

Input Tensor:
   tensor([[-0.3743, -1.3795, 0.7910, -0.8501],
      [-0.4872, 0.3542, -1.1613, 0.2766],
      [-0.0343, 0.6158, 1.5640, -1.5776]])
Target Tensor:
   tensor([[-0.1976, -0.5571, 0.0576, -0.6701],
      [ 0.3859, -0.4046, -1.3166, 0.0288],
      [ 0.7254, 0.5169, 0.2227, 0.9585]])
MAE loss: tensor(0.7236)

請注意,輸入和目標張量是二維張量,而平均絕對誤差是標量值。

示例2

在此示例中,我們計算2維輸入和目標張量之間的平均絕對誤差損失。這裡,輸入是一個需要引數requires_grad = True的張量。我們還計算關於輸入值的梯度。

# Import the required libraries
import torch
import torch.nn as nn

# define the input and target tensors
input = torch.randn(4, 5, requires_grad = True)
target = torch.randn(4, 5)

# print input and target tensors
print("Input Tensor:
", input) print("Target Tensor:
", target) # create a criterion to measure the mean absolute error loss = nn.L1Loss() # compute the loss (mean absolute error) output = loss(input, target) output.backward() print("MAE loss:", output) print("input.grad:
", input.grad)

輸出

Input Tensor:
   tensor([[-1.5325, 0.9718, 0.8848, -2.3685],
      [ 0.1574, -0.5296, -0.1587, -0.6423],
      [-1.9586, 0.6249, -1.1507, -1.7188]],
      requires_grad=True)
Target Tensor:
   tensor([[-0.2213, -1.0928, 0.1864, 0.6496],
      [ 0.9031, 1.3741, -0.9058, -2.0849],
      [-0.7316, -0.9297, -1.4479, 0.9797]])
MAE loss: tensor(1.4757, grad_fn=<L1LossBackward>)
input.grad:
   tensor([[-0.0833, 0.0833, 0.0833, -0.0833],
      [-0.0833, -0.0833, 0.0833, 0.0833],
      [-0.0833, 0.0833, 0.0833, -0.0833]])

請注意,在上面的輸出中,平均絕對誤差是一個grad函式(L1LossBackward)。梯度張量的尺寸與輸入張量相同。

更新於:2022年1月20日

瀏覽量:5K+

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.