📜  Python – PyTorch add() 方法

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

Python – PyTorch add() 方法

PyTorch torch.add()方法为输入张量的每个元素添加一个常数值,并返回一个新的修改后的张量。

让我们通过几个例子来看看这个概念:
示例 1:
# Importing the PyTorch library 
import torch 
    
# A constant tensor of size 6
a = torch.randn(6) 
print(a) 
    
# Applying the add function and 
# storing the result in 'b' 
b = torch.add(a, 5) 
print(b)

输出:

0.2403
 1.3826
-0.1763
-1.5177
-0.0555
 1.4558
[torch.FloatTensor of size 6]
 5.2403
 6.3826
 4.8237
 3.4823
 4.9445
 6.4558
[torch.FloatTensor of size 6]

示例 2:

# Importing the PyTorch library 
import torch 
    
# A constant tensor of size 6
a = torch.FloatTensor([1, 3, 8, 4, 10]) 
print(a) 
    
# Applying the add function and 
# storing the result in 'b' 
b = torch.add(a, 5) 
print(b) 

输出:

1
  3
  8
  4
 10
[torch.FloatTensor of size 5]
  6
  8
 13
  9
 15
[torch.FloatTensor of size 5]