如何计算 PyTorch 中张量元素的对数?
为了在PyTorch中计算张量元素的对数,我们使用该方法。它返回一个具有原始输入张量元素的自然对数值的新张量。它以张量作为输入参数并输出张量。torch.log()
脚步
导入所需的库。在以下所有Python示例中,所需的Python库是torch。确保您已经安装了它。
创建一个张量并打印它。
计算。这需要输入,一个张量,作为输入参数并且返回与所述的元件的自然对数值的新张量输入。torch.log(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程序显示了如何计算2D张量的自然对数。
# 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]])