PyTorch – 如何計算張量元素的邏輯 sigmoid 函式?


要計算張量元素的邏輯函式,我們使用 **torch.special.expit()** 方法。它返回一個新的張量,其中包含按元素計算的邏輯函式。它接受任何維度的 torch 張量。我們還可以應用 **torch.sigmoid()** 方法來計算張量元素的邏輯函式。它是 **torch.special.expit()** 方法的別名。

語法

torch.special.expit(input)
torch.sigmoid(input)

其中 **input** 是任何維度的 torch 張量。

步驟

我們可以使用以下步驟來按元素計算張量的邏輯 sigmoid 函式:

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

import torch
  • 定義一個 torch 張量。這裡我們定義了一個包含隨機數的 2D 張量。

tensor = torch.randn(2,3,3)
  • 使用 **torch.special.expit(input)** 或 **torch.sigmoid(input)** 計算張量的邏輯 sigmoid 函式。**input** 是任何維度的 torch 張量。可以選擇將此值賦給一個新變數

sig = torch.special.expit(tensor)
  • 列印計算出的邏輯 sigmoid 函式。

print("Entropy:", sig)

示例 1

在此程式中,我們使用 **torch.sigmoid()** 計算 1D 張量的 sigmoid 函式。

# import necessary libraries
import torch

# define a 1D tensor
tensor1 = torch.tensor([-1,2,0,.4,5])

# print above created tensor
print("Tensor:", tensor1)

# Compute the logistic sigmoid function of elements
sig = torch.sigmoid(tensor1)

# Display the computed Logistic Sigmoid function
print("Logistic Sigmoid:", sig)

輸出

Tensor: tensor([-1.0000, 2.0000, 0.0000, 0.4000, 5.0000])
Logistic Sigmoid: tensor([0.2689, 0.8808, 0.5000, 0.5987, 0.9933])

示例 2

在此程式中,我們使用 **torch.special.expit()** 計算 1D 和 2D 張量的 sigmoid 函式。

# import torch library
import torch

# define a 1D tensor
tensor1 = torch.tensor([-1,2,0,.4,5])

# print above created tensor
print("Tensor 1:", tensor1)

# compute the logistic sigmoid function of elements
sig1 = torch.special.expit(tensor1)

# Display the computed Logistic Sigmoid function
print("Logistic Sigmoid Function:
", sig1) # define a 2D tensor tensor2 = torch.randn(2,3,3) # print above created tensor print("Tensor 2:", tensor2) # compute the logistic sigmoid function of elements sig2 = torch.special.expit(tensor2) # Display the computed logistic sigmoid function print("Logistic Sigmoid Function:
", sig2)

輸出

Tensor 1: tensor([-1.0000, 2.0000, 0.0000, 0.4000, 5.0000])
Logistic Sigmoid Function:
   tensor([0.2689, 0.8808, 0.5000, 0.5987, 0.9933])
Tensor 2: tensor([[[-0.6318, -1.7586, 0.0252],
   [-0.0684, -0.4922, 1.7505],
   [-1.3301, 0.1333, -0.3744]],

   [[ 1.0607, -0.3999, 0.4564],
   [ 1.3029, 1.4259, 0.6266],
   [ 1.1038, 0.3965, 0.1522]]])
Logistic Sigmoid Function:
   tensor([[[0.3471, 0.1470, 0.5063],
      [0.4829, 0.3794, 0.8520],
      [0.2091, 0.5333, 0.4075]],

      [[0.7428, 0.4013, 0.6122],
      [0.7863, 0.8063, 0.6517],
      [0.7510, 0.5978, 0.5380]]])

更新於: 2022年1月7日

944 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.