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