Python PyTorch 中的 torch.nn.Dropout() 方法


神經網路訓練期間,將輸入張量中的一些隨機元素置零已被證明是一種有效的正則化技術。為實現此任務,我們可以應用 torch.nn.Dropout()。它將輸入張量中的某些元素置零。

元素將以給定的機率 p 置零。它使用伯努利分佈來對置零的元素進行取樣。不支援複數值輸入。

語法

torch.nn.Dropout(p=0.5)

元素置零的預設機率設定為 0.5

步驟

我們可以使用以下步驟以給定的機率 p − 隨機將輸入張量中的一些元素置零

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

import torch
  • 定義輸入張量 input

input = torch.randn(5,2)
  • 定義 Dropout 層 dropout,將其機率 p 作為一個可選引數傳遞。

dropout = torch.nn.Dropout(p= 0.5)
  • 對輸入張量 input 應用上述定義的 dropout 層 dropout。

output = dropout(input)
  • 列印包含 softmax 值的張量。

print(output)

示例 1

在以下 Python 程式中,我們使用 p = 0.5。它定義了元素置零的機率為 50%。

# Import the required library
import torch

# define a tensor
tensor = torch.randn(4)

# print the tensor
print("Input tensor:",tensor)

# define a dropout layer to randomly zero some elements
# with probability p=0.5
dropout = torch.nn.Dropout(.5)

# apply above defined dropout layer
output = dropout(tensor)

# print the output after dropout
print("Output Tensor:",output)

輸出

Input tensor: tensor([ 0.3667, -0.9647, 0.8537, 1.3171])
Output Tensor: tensor([ 0.7334, -1.9294, 0.0000, 0.0000])

示例 2

在以下 python3 程式中,我們使用 p = 0.25。這意味著輸入張量中的元素有 25% 的機會被置零。

# Import the required library
import torch

# define a tensor
tensor = torch.randn(4, 3)

# print the tensor
print("Input tensor:
",tensor) # define a dropout layer to randomly zero some elements # with probability p=0.25 dropout = torch.nn.Dropout(.25) # apply above defined dropout layer output = dropout(tensor) # print the output after dropout print("Output Tensor:
",output)

輸出

Input tensor:
   tensor([[-0.6748, -1.1602, 0.2891],
      [-0.7531, -1.3444, 0.2013],
      [-1.3212, 1.2103, -0.6457],
      [ 0.9957, -0.2670, 1.6593]])
Output Tensor:
   tensor([[-0.0000, -0.0000, 0.0000],
      [-1.0041, -0.0000, 0.2683],
      [-1.7616, 0.0000, -0.0000],
      [ 1.3276, -0.3560, 2.2124]])

更新於:2022 年 1 月 25 日

910 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.