Pytorch-张量相加的四种方法 / .item()用法


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
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM