詳解Pytorch中的tensor數(shù)據(jù)結構
torch.Tensor
torch.Tensor 是一種包含單一數(shù)據(jù)類型元素的多維矩陣,類似于 numpy 的 array。
Tensor 可以使用 torch.tensor() 轉換 Python 的 list 或序列數(shù)據(jù)生成,生成的是dtype 默認是 torch.FloatTensor。
注意
torch.tensor()總是拷貝 data。如果你有一個 Tensor data 并且僅僅想改變它的requires_grad屬性,可用requires_grad_()或者detach()來避免拷貝。如果你有一個numpy數(shù)組并且想避免拷貝,請使用torch.as_tensor()。
1,指定數(shù)據(jù)類型的 Tensor 可以通過傳遞參數(shù) torch.dtype 和/或者 torch.device 到構造函數(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 的內容可以通過 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() 方法從只有一個值的 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 會記錄相關的運算實現(xiàn)自動求導:
>>> 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,每一個 tensor都有一個相應的 torch.Storage 保存其數(shù)據(jù)。tensor 類提供了一個多維的、strided 視圖, 并定義了數(shù)值操作。
Tensor 數(shù)據(jù)類型
Torch 定義了七種 CPU tensor 類型和八種 GPU tensor 類型:

torch.Tensor 是默認的 tensor 類型(torch.FloatTensor)的簡稱,即 32 位浮點數(shù)數(shù)據(jù)類型。
Tensor 的屬性
Tensor 有很多屬性,包括數(shù)據(jù)類型、Tensor 的維度、Tensor 的尺寸。
- 數(shù)據(jù)類型:可通過改變 torch.tensor() 方法的 dtype 參數(shù)值,來設定不同的 tensor 數(shù)據(jù)類型。
- 維度:不同類型的數(shù)據(jù)可以用不同維度(dimension)的張量來表示。標量為 0 維張量,向量為 1 維張量,矩陣為 2 維張量。彩色圖像有 rgb 三個通道,可以表示為 3 維張量。視頻還有時間維,可以表示為 4 維張量,有幾個中括號 [ 維度就是幾??墒褂?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)程序輸出結果如下:

view 和 reshape 的區(qū)別
兩個方法都是用來改變 tensor 的 shape,view() 只適合對滿足連續(xù)性條件(contiguous)的 tensor 進行操作,而 reshape() 同時還可以對不滿足連續(xù)性條件的 tensor 進行操作。在滿足 tensor 連續(xù)性條件(contiguous)時,a.reshape() 返回的結果與a.view() 相同,都不會開辟新內存空間;不滿足 contiguous 時, 直接使用 view() 方法會失敗,reshape() 依然有用,但是會重新開辟內存空間,不與之前的 tensor 共享內存,即返回的是 ”副本“(等價于先調用 contiguous() 方法再使用 view() 方法)。
更多理解參考這篇文章
Tensor 與 ndarray
1,張量和 numpy 數(shù)組??梢杂?.numpy() 方法從 Tensor 得到 numpy 數(shù)組,也可以用 torch.from_numpy 從 numpy 數(shù)組得到Tensor。這兩種方法關聯(lián)的 Tensor 和 numpy 數(shù)組是共享數(shù)據(jù)內存的??梢杂脧埩康?clone方法拷貝張量,中斷這種關聯(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() 方法可以將張量轉換成 Python 數(shù)值和數(shù)值列表
# item方法和tolist方法可以將張量轉換成Python數(shù)值和數(shù)值列表 scalar = torch.tensor(5) # 標量 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ù)也可以傳維度,強烈建議 tensor() 傳數(shù)據(jù),Tensor() 傳維度,否則易搞混。
傳入維度的方法
| 方法名 | 方法功能 | 備注 |
|---|---|---|
torch.rand(*sizes, out=None) → Tensor | 返回一個張量,包含了從區(qū)間 [0, 1) 的均勻分布中抽取的一組隨機數(shù)。張量的形狀由參數(shù)sizes定義。 | 推薦 |
torch.randn(*sizes, out=None) → Tensor | 返回一個張量,包含了從標準正態(tài)分布(均值為0,方差為1,即高斯白噪聲)中抽取的一組隨機數(shù)。張量的形狀由參數(shù)sizes定義。 | 不推薦 |
torch.normal(means, std, out=None) → Tensor | 返回一個張量,包含了從指定均值 means 和標準差 std 的離散正態(tài)分布中抽取的一組隨機數(shù)。標準差 std 是一個張量,包含每個輸出元素相關的正態(tài)分布標準差。 | 多種形式,建議看源碼 |
torch.rand_like(a) | 根據(jù)數(shù)據(jù) a 的 shape 來生成隨機數(shù)據(jù) | 不常用 |
torch.randint(low=0, high, size) | 生成指定范圍(low, hight)和 size 的隨機整數(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 和 對角矩陣 | 簡單 |
樣例代碼:
>>> 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()
到此這篇關于Pytorch中的tensor數(shù)據(jù)結構的文章就介紹到這了,更多相關Pytorch tensor數(shù)據(jù)結構內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Python腳本zabbix自定義key監(jiān)控oracle連接狀態(tài)
這篇文章主要介紹了使用Python腳本zabbix自定義key監(jiān)控oracle連接狀態(tài),本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08
pycharm的console輸入實現(xiàn)換行的方法
今天小編就為大家分享一篇pycharm的console輸入實現(xiàn)換行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

