torch.sub() usage:
The screenshot of the official website introduction is as follows, followed by the interpretation of the official website introduction.
The interpretation is as follows:
函数形式:torch.
sub
(input, other, *, alpha=1, out=None)
Interpretation of parameters:
- input: the input minuend, the format is tensor format
- other: the subtrahend of the input
- alpha: Used in conjunction with the other parameter above to multiply it with other. When the value of alpha is not specified when using the torch.sub() function, alpha defaults to 1
- out: Specifies the variable to which the output value of torch.sub() is assigned, and may not be specified.
Function output calculation formula:
For example:
>>> a = torch.tensor((1, 2))
>>> b = torch.tensor((0, 1))
>>> c = torch.sub(a, b, alpha=2)
>>> print(c)
tensor([1, 0])
'''
结合计算公式可知:c1 = a1 - alpha*b1 = 1 - 2*0 = 1 ;c2 = a2 - alpha*b2 = 2 - 2*1 = 0
'''
The function of torch.sub_() is the same as torch.sub(), the difference is that torch.sub_() is the in-place operation version of torch.sub().
The in-place operation is an operation that directly changes the content of a given linear algebra, vector, matrix (tensor) without copying. The code effect is as follows:
>>> a = torch.tensor((1, 2))
>>> b = torch.tensor((0, 1))
>>> a.sub_(b, alpha=2)
>>> print(a)
tensor([1, 0])
'''
可见对a直接用调用方法的形式使用torch.sub_()可以直接将a原先的值修改为torch.sub(a,b,alpha=2)的运算结果
'''
It is worth mentioning that all operations with "_" in the name in Torch are in-place.