PyTorch - torch.log2() 方法
我們使用 torch.log2() 方法計算張量元素的以 2 為底的對數。它返回一個新張量,其中包含原始輸入張量中元素的對數值。它採用一個張量作為輸入引數,並輸出一個張量。
語法
torch.log2(input)
其中 input 是 PyTorch 張量。
它返回一個包含以 2 為底的對數值的新張量。
步驟
匯入 torch 庫。確保你已經安裝了它。
import torch
建立一個張量並列印它。
tensor1 = torch.rand(5,3)
print("Tensor:", tensor1)計算 torch.log2(input),並可以選擇將這個值賦予一個新變數。此處,input 是建立的張量。
logb2 = torch.log2(tensor1)
列印結果張量。
print("logarithm base 2 of elements:
",logb2)示例 1
以下 Python 程式展示瞭如何在 PyTorch 中計算輸入張量元素的以 2 為底的對數。
# import torch library
import torch
# create a 2D tensor
tensor1 = torch.rand(5,3)
print("Tensor:", tensor1)
# compute logarithm base 2 of the elements of above tensor
logb2 = torch.log2(tensor1)
print("logarithm base 2 of elements:
",logb2)輸出
Tensor: tensor([[0.5755, 0.3263, 0.3598], [0.0498, 0.0915, 0.0119], [0.6760, 0.6329, 0.7446], [0.5575, 0.6406, 0.2418], [0.4944, 0.7194, 0.9808]]) logarithm base 2 of elements: tensor([[-0.7970, -1.6158, -1.4749], [-4.3272, -3.4495, -6.3959], [-0.5650, -0.6599, -0.4255], [-0.8430, -0.6426, -2.0480], [-1.0162, -0.4751, -0.0279]])
示例 2
# import required library
import torch
# create a 1D tensor
t = torch.tensor([1,2,3,4,5])
print("Tensor:", tensor1)
# compute logarithm base 2 of the elements of above tensor
logb2 = torch.log2(t)
print("logarithm base 2:
",logb2)輸出
Tensor: tensor([1, 2, 3, 3, 4, 5]) logarithm base 2: tensor([0.0000, 1.0000, 1.5850, 2.0000, 2.3219])
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP