PyTorch – 如何计算输入张量的逐元素熵?
要计算输入张量的逐元素熵,我们使用 **torch.special.entr()** 方法。它返回一个新的张量,其中包含逐元素计算的熵。
如果张量的元素为负数,则熵为 **负无穷大**。
如果张量的元素为零,则熵为 **零**。
正数元素的熵计算为元素与其自然对数乘积的负值。它接受任何维度的 torch 张量。
步骤
我们可以使用以下步骤来逐元素计算张量的熵:
导入所需的库。在以下所有示例中,所需的 Python 库为 **torch**。确保您已安装它。
import torch
定义一个 torch 张量。这里我们定义了一个包含随机数的二维张量。
tensor = torch.randn(2,3,3)
使用 **torch.special.entr(tensor)** 计算上述定义的张量的熵。可以选择将此值赋给一个新变量。
ent = torch.special.entr(tensor)
打印计算出的熵。
print("Entropy:", ent)示例 1
在此示例中,我们计算了一个一维用户定义张量的熵。
# import necessary libraries
import torch
# define a 1D tensor
tensor1 = torch.tensor([-1,1,2,0,.4])
# print above created tensor
print("Tensor:", tensor1)
# compute the entropy on input tensor element wise
ent = torch.special.entr(tensor1)
# Display the computed entropies
print("Entropy:", ent)输出
它将产生以下输出:
Tensor: tensor([-1.0000, 1.0000, 2.0000, 0.0000, 0.4000]) Entropy: tensor([ -inf, -0.0000, -1.3863, 0.0000, 0.3665])
请注意,负数的熵为 -inf,零的熵为零。
示例 2
在此示例中,我们逐元素计算了一个二维 torch 张量的熵。
# import necessary libraries
import torch
# define a tensor of random numbers
tensor1 = torch.randn(2,3,3)
# print above created tensor
print("Tensor:
", tensor1)
# compute the entropy on input tensor element wise
ent = torch.special.entr(tensor1)
# Display the computed entropies
print("Entropy:
", ent)输出
它将产生以下输出:
Tensor: tensor([[[ 0.5996, -0.7526, -1.0233], [-0.9907, -0.0358, 0.6433], [ 0.4527, -0.1434, 0.3338]], [[ 0.0521, -0.3729, -0.1162], [ 0.2417, 0.7732, -0.6362], [-0.7942, -0.2582, 1.0860]]]) Entropy: tensor([[[ 0.3067, -inf, -inf], [ -inf, -inf, 0.2838], [ 0.3588, -inf, 0.3663]], [[ 0.1539, -inf, -inf], [ 0.3432, 0.1989, -inf], [ -inf, -inf, -0.0896]]])
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP