Pytorch-張量相加的四種方法 / .item()用法
相關基本操作:http://pytorch.org/docs/torch.
這里舉例說明:
x = torch.rand(5, 3) y = torch.rand(5, 3) #第一種 print(x + y) #第二種 print(torch.add(x, y)) #第三種 result = torch.empty(5, 3) torch.add(x, y, out=result) print(result) #第四種 y.add_(x) print(y)
Any operation that mutates a tensor in-place is post-fixed with an . For example: x.copy(y), x.t_(), will change x.
關於x.item()用法:
文檔中給了例子,說是一個元素張量可以用item得到元素值,請注意這里的print(x)和print(x.item())值是不一樣的,一個是打印張量,一個是打印元素:
x = torch.randn(1)
print(x) print(x.item()) #結果是 tensor([-0.4464]) -0.44643348455429077
那么如果x不是只含一個元素張量可以嗎?本菜試了一下,不行的!但是可以用這種方法訪問特定位置的元素~
x = torch.randn(2, 2)
print(x[1, 1]) print(x[1, 1].item()) #結果 tensor(0.4279) 0.4278833866119385 ···
作者:spectre_hola
鏈接:https://www.jianshu.com/p/be3276b434b2
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。