Pytorch-张量相加的四种方法 / .item()用法
生活随笔
收集整理的這篇文章主要介紹了
Pytorch-张量相加的四种方法 / .item()用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文連接:https://blog.csdn.net/weixin_36670529/article/details/105940377
這里舉例說明:
# -- coding: utf-8 -- import torchx = torch.rand(5, 3) y = torch.rand(5, 3) print("x:\n", x) print("y:\n", y)# 第一種 print("method 1:\n", x + y) # 第二種 print("method 2:\n", torch.add(x, y)) # 第三種 result = torch.empty(5, 3) torch.add(x, y, out=result) print("method 3:\n", result) # 第四種 y.add_(x) print("method 4:\n", y) x:tensor([[0.2839, 0.9364, 0.2337],[0.4001, 0.9134, 0.2568],[0.5010, 0.6690, 0.5995],[0.1166, 0.9743, 0.9053],[0.2917, 0.4442, 0.9245]]) y:tensor([[0.5839, 0.8467, 0.3166],[0.4876, 0.0694, 0.2991],[0.5943, 0.7027, 0.0034],[0.2299, 0.3224, 0.9445],[0.5194, 0.3128, 0.8982]]) method 1:tensor([[0.8679, 1.7831, 0.5503],[0.8877, 0.9828, 0.5558],[1.0953, 1.3718, 0.6029],[0.3464, 1.2967, 1.8498],[0.8111, 0.7570, 1.8228]]) method 2:tensor([[0.8679, 1.7831, 0.5503],[0.8877, 0.9828, 0.5558],[1.0953, 1.3718, 0.6029],[0.3464, 1.2967, 1.8498],[0.8111, 0.7570, 1.8228]]) method 3:tensor([[0.8679, 1.7831, 0.5503],[0.8877, 0.9828, 0.5558],[1.0953, 1.3718, 0.6029],[0.3464, 1.2967, 1.8498],[0.8111, 0.7570, 1.8228]]) method 4:tensor([[0.8679, 1.7831, 0.5503],[0.8877, 0.9828, 0.5558],[1.0953, 1.3718, 0.6029],[0.3464, 1.2967, 1.8498],[0.8111, 0.7570, 1.8228]])關于x.item()用法:
文檔中給了例子,說是一個元素張量可以用item得到元素值,請注意這里的print(x)和print(x.item())值是不一樣的,一個是打印張量,一個是打印元素:
那么如果x不是只含一個元素張量可以嗎?本菜試了一下,不行的!但是可以用這種方法訪問特定位置的元素:
x = torch.randn(2, 2) # print(x.item()) # ValueError: only one element tensors can be converted to Python scalars print(x[1, 1]) # tensor(0.4471) print(x[1, 1].item()) # 0.4471171200275421總結
以上是生活随笔為你收集整理的Pytorch-张量相加的四种方法 / .item()用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浙江大学人工智能研究所:AI+X驱动科学
- 下一篇: 领扣(LeetCode)二叉树的所有路径