如何在PyTorch中計算張量元素的對數?
在PyTorch中計算張量元素的對數,我們使用**torch.log()**方法。它返回一個新的張量,其中包含原始輸入張量元素的自然對數值。它以張量作為輸入引數,並輸出一個張量。
步驟
匯入所需的庫。在以下所有Python示例中,所需的Python庫是**torch**。確保你已經安裝了它。
建立一個張量並列印它。
計算**torch.log(input)**。它以**input**(一個張量)作為輸入引數,並返回一個新的張量,其中包含**input**元素的自然對數值。
列印包含原始輸入張量元素自然對數值的張量。
示例1
下面的Python程式演示瞭如何計算PyTorch張量的自然對數。
# import necessary library
import torch
# Create a tensor
t = torch.Tensor([2.3,3,2.3,4,3.4])
# print the above created tensor
print("Original tensor:\n", t)
# compute the logarithm of elements of the above tensor
log = torch.log(t)
# print the computed logarithm of elements
print("Logarithm of Elements:\n", log)輸出
Original tensor: tensor([2.3000, 3.0000, 2.3000, 4.0000, 3.4000]) Logrithm of Elements: tensor([0.8329, 1.0986, 0.8329, 1.3863, 1.2238])
示例2
下面的Python程式演示瞭如何計算二維張量的自然對數。
# import necessary libraries
import torch
# Create a tensor of random numbers of size 3x4
t = torch.rand(3,4)
# print the above created tensor
print("Original tensor:\n", t)
# compute the logarithm of elements of the above tensor
log = torch.log(t)
# print the computed logarithm of elements
print("Logarithm of Elements:\n", log)輸出
Original tensor: tensor([[0.1245, 0.0448, 0.1176, 0.7607], [0.7415, 0.7738, 0.0694, 0.6983], [0.8371, 0.6169, 0.3858, 0.8027]]) Logarithm of Elements: tensor([[-2.0837, -3.1048, -2.1405, -0.2735], [-0.2990, -0.2565, -2.6676, -0.3591], [-0.1778, -0.4830, -0.9524, -0.2198]])
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP