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]]])
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP