如何在PyTorch中計算輸入中每個元素的海維賽德階躍函式?


要計算輸入張量中每個元素的海維賽德階躍函式,我們使用 **torch.heaviside()** 方法。它接受兩個引數 - 輸入和值。它返回一個包含計算出的 **heaviside** 階躍函式的新張量。

如果 **input=0**,則 **heaviside** 函式的值與值相同。如果輸入小於零,則heaviside的值為零。如果輸入大於零,則 **heaviside** 的值為1。它接受任何維度的torch張量。它也稱為 **單位階躍函式**。

語法

torch.heaviside(input, values)

步驟

我們可以使用以下步驟計算海維賽德階躍函式:

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

import torch
  • 建立兩個張量 - **input** 和 **values**。

input = torch.randn(3,3)
values = torch.tensor([0.5, 0.3, 0.7])
  • 使用 **torch.heaviside(input, values)** 計算上述定義的張量的海維賽德階躍函式。可以選擇將此值賦值給一個新變數。

hssf = torch.heaviside(input, values)
  • 列印上述計算出的海維賽德階躍函式。

print("Heaviside Step Function:
", hssf)

示例1

在這個Python示例中,我們計算一維張量的海維賽德階躍函式。

import torch
# define input and values tensors
input = torch.tensor([-1.5, 0, 2.0])
values = torch.tensor([0.5])

# display above defined tensors
print("Input Tensor:
", input) print("Values Tensor:
", values) # compute heaviside step function hssf = torch.heaviside(input, values) print("Heaviside Step Function:
", hssf)

輸出

Input Tensor:
   tensor([-1.5000, 0.0000, 2.0000])
Values Tensor:
   tensor([0.5000])
Heaviside Step Function:
   tensor([0.0000, 0.5000, 1.0000])

示例2

在這個示例中,我們計算二維張量的海維賽德階躍函式。

import torch
# define input and values tensors
input = torch.tensor([[0.2, 0.0, -0.7, -0.2],
   [0.0, 0.6, 0.6, -0.9],
   [0.0, 0.0, 0.0, 0.4],
   [-1.2, 0.0, 0.8, 0.0]])
values = torch.tensor([0.5,0.3, 0.7, 0.8])

# display above defined tensors
print("Input Tensor:
", input) print("Values Tensor:
", values) # compute heaviside step function hssf = torch.heaviside(input, values) print("Heaviside Step Function:
", hssf)

輸出

Input Tensor:
   tensor([[ 0.2000, 0.0000, -0.7000, -0.2000],
      [ 0.0000, 0.6000, 0.6000, -0.9000],
      [ 0.0000, 0.0000, 0.0000, 0.4000],
      [-1.2000, 0.0000, 0.8000, 0.0000]])
Values Tensor:
   tensor([5.0000, 0.3000, 0.7000, 0.8000])
Heaviside Step Function:
   tensor([[1.0000, 0.3000, 0.0000, 0.0000],
      [5.0000, 1.0000, 1.0000, 0.0000],
      [5.0000, 0.3000, 0.7000, 1.0000],
      [0.0000, 0.3000, 1.0000, 0.8000]])

更新於:2022年1月27日

310 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告