網(wǎng)站首頁 編程語言 正文
torch.Tensor
torch.Tensor
是一種包含單一數(shù)據(jù)類型元素的多維矩陣,類似于 numpy 的 array
。
Tensor 可以使用 torch.tensor() 轉(zhuǎn)換 Python 的 list 或序列數(shù)據(jù)生成,生成的是dtype
默認(rèn)是 torch.FloatTensor
。
注意
torch.tensor()
總是拷貝 data。如果你有一個(gè) Tensor data 并且僅僅想改變它的requires_grad
屬性,可用requires_grad_()
或者detach()
來避免拷貝。如果你有一個(gè)numpy
數(shù)組并且想避免拷貝,請(qǐng)使用torch.as_tensor()
。
1,指定數(shù)據(jù)類型的 Tensor 可以通過傳遞參數(shù) torch.dtype
和/或者 torch.device
到構(gòu)造函數(shù)生成:
注意為了改變已有的 tensor 的 torch.device 和/或者 torch.dtype, 考慮使用
to()
方法.
>>> torch.ones([2,3], dtype=torch.float64, device="cuda:0") tensor([[1., 1., 1.], [1., 1., 1.]], device='cuda:0', dtype=torch.float64) >>> torch.ones([2,3], dtype=torch.float32) tensor([[1., 1., 1.], [1., 1., 1.]])
2,Tensor 的內(nèi)容可以通過 Python索引或者切片訪問以及修改:
>>> matrix = torch.tensor([[2,3,4],[5,6,7]]) >>> print(matrix[1][2]) tensor(7) >>> matrix[1][2] = 9 >>> print(matrix) tensor([[2, 3, 4], [5, 6, 9]])
3,使用 torch.Tensor.item()
或者 int()
方法從只有一個(gè)值的 Tensor中獲取 Python Number:
>>> x = torch.tensor([[4.5]]) >>> x tensor([[4.5000]]) >>> x.item() 4.5 >>> int(x) 4
4,Tensor可以通過參數(shù) requires_grad=True
創(chuàng)建, 這樣 torch.autograd
會(huì)記錄相關(guān)的運(yùn)算實(shí)現(xiàn)自動(dòng)求導(dǎo):
>>> x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True) >>> out = x.pow(2).sum() >>> out.backward() >>> x.grad tensor([[ 2.0000, -2.0000], [ 2.0000, 2.0000]])
5,每一個(gè) tensor都有一個(gè)相應(yīng)的 torch.Storage
保存其數(shù)據(jù)。tensor 類提供了一個(gè)多維的、strided 視圖, 并定義了數(shù)值操作。
Tensor 數(shù)據(jù)類型
Torch 定義了七種 CPU tensor 類型和八種 GPU tensor 類型:
torch.Tensor
是默認(rèn)的 tensor 類型(torch.FloatTensor
)的簡稱,即 32
位浮點(diǎn)數(shù)數(shù)據(jù)類型。
Tensor 的屬性
Tensor 有很多屬性,包括數(shù)據(jù)類型、Tensor 的維度、Tensor 的尺寸。
- 數(shù)據(jù)類型:可通過改變 torch.tensor() 方法的 dtype 參數(shù)值,來設(shè)定不同的 tensor 數(shù)據(jù)類型。
- 維度:不同類型的數(shù)據(jù)可以用不同維度(dimension)的張量來表示。標(biāo)量為 0 維張量,向量為 1 維張量,矩陣為 2 維張量。彩色圖像有 rgb 三個(gè)通道,可以表示為 3 維張量。視頻還有時(shí)間維,可以表示為 4 維張量,有幾個(gè)中括號(hào) [ 維度就是幾。可使用 dim() 方法 獲取 tensor 的維度。
- 尺寸:可以使用 shape屬性或者 size()方法查看張量在每一維的長度,可以使用 view()方法或者reshape() 方法改變張量的尺寸。
樣例代碼如下:
matrix = torch.tensor([[[1,2,3,4],[5,6,7,8]], [[5,4,6,7], [5,6,8,9]]], dtype = torch.float64) print(matrix) # 打印 tensor print(matrix.dtype) # 打印 tensor 數(shù)據(jù)類型 print(matrix.dim()) # 打印 tensor 維度 print(matrix.size()) # 打印 tensor 尺寸 print(matrix.shape) # 打印 tensor 尺寸 matrix2 = matrix.view(4, 2, 2) # 改變 tensor 尺寸 print(matrix2)
程序輸出結(jié)果如下:
view 和 reshape 的區(qū)別
兩個(gè)方法都是用來改變 tensor 的 shape,view() 只適合對(duì)滿足連續(xù)性條件(contiguous
)的 tensor 進(jìn)行操作,而 reshape() 同時(shí)還可以對(duì)不滿足連續(xù)性條件的 tensor 進(jìn)行操作。在滿足 tensor 連續(xù)性條件(contiguous
)時(shí),a.reshape() 返回的結(jié)果與a.view() 相同,都不會(huì)開辟新內(nèi)存空間;不滿足 contiguous
時(shí), 直接使用 view() 方法會(huì)失敗,reshape()
依然有用,但是會(huì)重新開辟內(nèi)存空間,不與之前的 tensor 共享內(nèi)存,即返回的是 ”副本“(等價(jià)于先調(diào)用 contiguous()
方法再使用 view()
方法)。
更多理解參考這篇文章
Tensor 與 ndarray
1,張量和 numpy 數(shù)組。可以用 .numpy()
方法從 Tensor 得到 numpy 數(shù)組,也可以用 torch.from_numpy
從 numpy 數(shù)組得到Tensor。這兩種方法關(guān)聯(lián)的 Tensor 和 numpy 數(shù)組是共享數(shù)據(jù)內(nèi)存的。可以用張量的 clone
方法拷貝張量,中斷這種關(guān)聯(lián)。
arr = np.random.rand(4,5) print(type(arr)) tensor1 = torch.from_numpy(arr) print(type(tensor1)) arr1 = tensor1.numpy() print(type(arr1)) """ <class 'numpy.ndarray'> <class 'torch.Tensor'> <class 'numpy.ndarray'> """
2,item()
方法和 tolist()
方法可以將張量轉(zhuǎn)換成 Python 數(shù)值和數(shù)值列表
# item方法和tolist方法可以將張量轉(zhuǎn)換成Python數(shù)值和數(shù)值列表 scalar = torch.tensor(5) # 標(biāo)量 s = scalar.item() print(s) print(type(s)) tensor = torch.rand(3,2) # 矩陣 t = tensor.tolist() print(t) print(type(t)) """ 1.0 <class 'float'> [[0.8211846351623535, 0.20020723342895508], [0.011571824550628662, 0.2906131148338318]] <class 'list'> """
創(chuàng)建 Tensor
創(chuàng)建 tensor ,可以傳入數(shù)據(jù)或者維度,torch.tensor() 方法只能傳入數(shù)據(jù),torch.Tensor() 方法既可以傳入數(shù)據(jù)也可以傳維度,強(qiáng)烈建議 tensor() 傳數(shù)據(jù),Tensor() 傳維度,否則易搞混。
傳入維度的方法
方法名 | 方法功能 | 備注 |
---|---|---|
torch.rand(*sizes, out=None) → Tensor |
返回一個(gè)張量,包含了從區(qū)間 [0, 1) 的均勻分布中抽取的一組隨機(jī)數(shù)。張量的形狀由參數(shù)sizes定義。 |
推薦 |
torch.randn(*sizes, out=None) → Tensor |
返回一個(gè)張量,包含了從標(biāo)準(zhǔn)正態(tài)分布(均值為0,方差為1,即高斯白噪聲)中抽取的一組隨機(jī)數(shù)。張量的形狀由參數(shù)sizes定義。 | 不推薦 |
torch.normal(means, std, out=None) → Tensor |
返回一個(gè)張量,包含了從指定均值 means 和標(biāo)準(zhǔn)差 std 的離散正態(tài)分布中抽取的一組隨機(jī)數(shù)。標(biāo)準(zhǔn)差 std 是一個(gè)張量,包含每個(gè)輸出元素相關(guān)的正態(tài)分布標(biāo)準(zhǔn)差。 |
多種形式,建議看源碼 |
torch.rand_like(a) |
根據(jù)數(shù)據(jù) a 的 shape 來生成隨機(jī)數(shù)據(jù) |
不常用 |
torch.randint(low=0, high, size) |
生成指定范圍(low, hight )和 size 的隨機(jī)整數(shù)數(shù)據(jù) |
常用 |
torch.full([2, 2], 4) |
生成給定維度,全部數(shù)據(jù)相等的數(shù)據(jù) | 不常用 |
torch.arange(start=0, end, step=1, *, out=None) |
生成指定間隔的數(shù)據(jù) | 易用常用 |
torch.ones(*size, *, out=None) |
生成給定 size 且值全為1 的矩陣數(shù)據(jù) | 簡單 |
zeros()/zeros_like()/eye() |
全 0 的 tensor 和 對(duì)角矩陣 |
簡單 |
樣例代碼:
>>> torch.rand([1,1,3,3]) tensor([[[[0.3005, 0.6891, 0.4628], [0.4808, 0.8968, 0.5237], [0.4417, 0.2479, 0.0175]]]]) >>> torch.normal(2, 3, size=(1, 4)) tensor([[3.6851, 3.2853, 1.8538, 3.5181]]) >>> torch.full([2, 2], 4) tensor([[4, 4], [4, 4]]) >>> torch.arange(0,10,2) tensor([0, 2, 4, 6, 8]) >>> torch.eye(3,3) tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
參考資料
PyTorch:view() 與 reshape() 區(qū)別
詳解torch.rand和torch.randn和torch.normal和linespace()
原文鏈接:https://blog.csdn.net/qq_20986663/article/details/126781131
相關(guān)推薦
- 2023-02-27 Python?input()函數(shù)案例教程_python
- 2022-12-29 Kotlin?協(xié)程思維模型的引入使用建立_Android
- 2022-07-28 pytest使用parametrize將參數(shù)化變量傳遞到fixture_python
- 2022-06-21 C語言詳解如何實(shí)現(xiàn)帶頭雙向循環(huán)鏈表_C 語言
- 2022-02-16 mac 使用launchctl 開機(jī)時(shí)加速vim、emacs
- 2022-06-12 Python數(shù)據(jù)傳輸黏包問題_python
- 2022-10-01 iOS簡單實(shí)現(xiàn)輪播圖效果_IOS
- 2022-09-30 Python3中map()、reduce()、filter()的用法詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支