日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/10/8 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 = torch.randn(1) print(x) # tensor([0.5613]) print(x.item()) # 0.5612506866455078

那么如果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()用法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。