📜  Python PyTorch – rsqrt() 方法

📅  最后修改于: 2022-05-13 01:55:01.655000             🧑  作者: Mango

Python PyTorch – rsqrt() 方法

PyTorch rsqrt() 方法计算输入张量的每个元素的平方根的倒数。它接受实值和复值张量。它返回“ NaN ”(不是数字)作为负数平方根的倒数,“ inf ”表示零。在数学上,以下公式用于计算数字输入的平方根的倒数。

out = 1/(input)^(1/2)

rsqrt()函数:

示例 1:

在这个例子中,我们使用torch.rsqrt()方法来计算一维浮点张量的平方根的倒数。张量也由零和负数组成。这里,输入张量的第三个元素是零,零的rsqrt是'inf',它的第四个元素是负数,它的rsqrt是'nan'。

Python3
# Python program to compute the reciprocal of
# square root of a tensor
# importing torch
import torch
  
# define the input tensor
a = torch.tensor([1.2, 0.32, 0., -32.3, 4.])
  
# print the input tenosr
print("tensor a:\n", a)
  
# compute reciprocal square root
result = torch.rsqrt(a)
  
# print the computed result
print("rsqrt of a:\n", result)


Python3
# Python program to compute the reciprocal of
# square root of a complex tensor
# importing torch
import torch
  
# define the input tensor
a = torch.randn(4, dtype=torch.cfloat)
  
# print the input tensor
print("tensor a:\n", a)
  
# compute reciprocal square root
result = torch.rsqrt(a)
  
# print the computed result
print("rsqrt of a:\n", result)


Python3
# Python program to compute the reciprocal of
# square root of a multi-dimensional tensor
# importing torch
import torch
  
# define the input tensor
a = torch.randn(2, 3, 2)
  
# print the input tensor
print("tensor a:\n", a)
  
# compute reciprocal square root
result = torch.rsqrt(a)
  
# print the computed result
print("rsqrt of a:\n", result)


输出:

tensor a:
 tensor([  1.2000,   0.3200,   0.0000, -32.3000,   4.0000])
rsqrt of a:
 tensor([0.9129, 1.7678,    inf,    nan, 0.5000])

示例 2:

在下面的示例中,我们使用torch.rsqrt()方法计算一维复数张量的 rsqrt。请注意,复数是使用随机生成器生成的,因此您可能会注意到每次运行都会得到不同的数字。

Python3

# Python program to compute the reciprocal of
# square root of a complex tensor
# importing torch
import torch
  
# define the input tensor
a = torch.randn(4, dtype=torch.cfloat)
  
# print the input tensor
print("tensor a:\n", a)
  
# compute reciprocal square root
result = torch.rsqrt(a)
  
# print the computed result
print("rsqrt of a:\n", result)

输出:

示例 3:

在下面的示例中,我们使用torch.rsqrt()方法计算 3-D 张量的 rsqrt。在此示例中,我们还将使用随机生成器生成数字,因此您可能会注意到每次运行都会得到不同的数字。以与一维张量相同的方式,计算多维张量的每个元素的 rsqrt。

Python3

# Python program to compute the reciprocal of
# square root of a multi-dimensional tensor
# importing torch
import torch
  
# define the input tensor
a = torch.randn(2, 3, 2)
  
# print the input tensor
print("tensor a:\n", a)
  
# compute reciprocal square root
result = torch.rsqrt(a)
  
# print the computed result
print("rsqrt of a:\n", result)

输出:

tensor a:
 tensor([[[-0.7205, -1.3897],
         [ 1.0028,  0.3652],
         [ 0.8731, -0.7459]],

        [[-0.9512,  1.8421],
         [ 0.2855,  0.3749],
         [-0.8577,  0.6472]]])
rsqrt of a:
 tensor([[[   nan,    nan],
         [0.9986, 1.6547],
         [1.0702,    nan]],

        [[   nan, 0.7368],
         [1.8715, 1.6333],
         [   nan, 1.2431]]])