Pytorch數據類型以及創建張量! |
一. 數據類型
- Python和Pytorch類型(Pytorch是面向計算的GPU加速庫,沒有提供對String支持的)
- 怎樣去表示String呢?
- 第1種方法:利用One-hot 編碼進行表示
- 第2中方法:Embedding-常用的編碼器有Word2vec, glove
1.1. 如何判斷數據的類型?
In [1]: import torch
In [2]: a = torch.randn(2,3)
In [3]: a.type()
Out[3]: 'torch.FloatTensor'
In [4]: type(a)
Out[4]: torch.Tensor
In [5]: isinstance(a, torch.FloatTensor)
Out[5]: True
In [6]: isinstance(a, torch.cuda.DoubleTensor)
Out[6]: False
In [7]: data = a.cuda()
In [9]: isinstance(data, torch.cuda.FloatTensor)
Out[9]: True
這裏:
x.cuda()
會返回一個GPU
上面的引用。
1.2. Dim爲0的標量
- 標量的dimmesion=0或者rank=0
In [10]: torch.tensor(1.)
Out[10]: tensor(1.)
In [11]: torch.tensor(1.3)
Out[11]: tensor(1.3000)
這裏: 1.3是0維的,但是[1.3]是1維的,長度爲1的Tensor。
- 如何確定其shape
In [16]: a = torch.tensor(1.1)
In [17]: a.shape
Out[17]: torch.Size([])
In [18]: a.size()
Out[18]: torch.Size([])
In [19]: len(a.shape)
Out[19]: 0
1.3. Dim爲1的vector
torch.tensor()
接受的是數據的內容。
In [23]: torch.tensor([1.1])
Out[23]: tensor([1.1000])
In [24]: torch.tensor([1.1, 2, 2.2])
Out[24]: tensor([1.1000, 2.0000, 2.2000])
torch.FloatTensor()
接受的是數據的shape。初始化方式爲random初始化。
In [28]: torch.FloatTensor(1)
Out[28]: tensor([8.0223e-24])
In [29]: torch.FloatTensor(2)
Out[29]: tensor([0., 0.])
In [30]: torch.FloatTensor(3)
Out[30]: tensor([0., 0., 0.])
- 從Numpy中引入。
torch.from_numpy(data)
爲numpy轉爲tensor類型。
In [37]: data = np.ones(2)
In [38]: data
Out[38]: array([1., 1.])
In [39]: torch.from_numpy(data)
Out[39]: tensor([1., 1.], dtype=torch.float64)
In [41]: a = torch.ones(2)
In [42]: a
Out[42]: tensor([1., 1.])
In [43]: a.shape
Out[43]: torch.Size([2])
1.4. Dim爲2的tensor
- 隨機正太分佈初始化。
In [45]: a = torch.randn(2, 3)
In [46]: a
Out[46]:
tensor([[ 0.3851, 0.1789, 0.5019],
[ 0.0416, -0.6383, -1.4668]])
In [47]: a.shape
Out[47]: torch.Size([2, 3])
In [48]: a.size
Out[48]: <function Tensor.size>
In [49]: a.size(0)
Out[49]: 2
In [50]: a.size(1)
Out[50]: 3
In [52]: a.shape[0]
Out[52]: 2
1.5. Dim爲3的tensor
- 隨機均勻分佈初始化。
In [54]: a = torch.rand(1, 2, 3)
In [55]: a
Out[55]:
tensor([[[0.2390, 0.8743, 0.2872],
[0.4887, 0.8119, 0.9755]]])
In [56]: a.shape
Out[56]: torch.Size([1, 2, 3])
In [57]: a[0]
Out[57]:
tensor([[0.2390, 0.8743, 0.2872],
[0.4887, 0.8119, 0.9755]])
In [58]: list(a.shape)
Out[58]: [1, 2, 3]
1.6. Dim爲4的tensor
- 四維的適合圖片這種類型,CNN中:。
In [60]: a = torch.rand(2,3,28,28)
In [61]: a
Out[61]:
tensor([[[[0.4719, 0.1398, 0.6847, ..., 0.0918, 0.0143, 0.1143],
[0.6387, 0.9712, 0.5633, ..., 0.3985, 0.0044, 0.8570],
[0.6903, 0.4872, 0.6161, ..., 0.1309, 0.4488, 0.8872],
...,
...,
[0.0207, 0.4922, 0.5937, ..., 0.7938, 0.8883, 0.3471],
[0.7633, 0.1084, 0.9482, ..., 0.8388, 0.1114, 0.6074],
[0.9635, 0.3892, 0.1995, ..., 0.7625, 0.0072, 0.7886]]]])
In [62]: a.shape
Out[62]: torch.Size([2, 3, 28, 28])
二. 創建Tensor
2.1. Import from numpy
import torch
import numpy as np
print(torch.__version__)
print(torch.cuda.is_available())
a = np.array([2, 3.3])
print(torch.from_numpy(a))
b = np.ones([2, 3])
print(torch.from_numpy(b))
- 運行結果
1.3.1
True
tensor([2.0000, 3.3000], dtype=torch.float64)
tensor([[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
Process finished with exit code 0
這裏: 從numpy導入的float其實是double類型。
2.2. Import from List
- 如果數據量不是太大,可以從List中導入。不需要Numpy作爲一個載體。
import torch
import numpy as np
print(torch.__version__)
print(torch.cuda.is_available())
a = torch.tensor([2., 3.2]) # 小寫的tensor()接受的是數據的內容;
print(a)
b = torch.FloatTensor([2., 3.2]) # 大寫也可以接受數據,必須用list,不建議用這個。
print(b)
print(torch.FloatTensor(2, 3)) # 大寫的Tensor()接受的維度;
這裏: 建議以後把小寫的tensor接受內容,把Tensor接受維度,不然容易混淆。
2.3. 生成未初始化的數據
- uninitialized的數據,首先要申請一片內存空間,直接使用torch.empty(shape)函數。未初始化的數據也是有數據的,只是random。
import torch
import numpy as np
# 1.未初始化的數據!
a = torch.empty(1)
print(a)
# 2.未初始化的數據!生成的數據十分不規則!有的過大,有的過小。
print(torch.Tensor(2, 3))
print(torch.IntTensor(2, 3))
這裏: 未初始化的api可以使用,但是隻是作爲一個容器,後面要把這些數據覆蓋掉,不然可能早成一系列問題。
2.4. set default type
- pytorch中一個默認的類型(FlaotTensor),如果你設置了默認的類型,使用的就是默認的類型。
import torch
import numpy as np
print(torch.tensor([1.2, 3]).type())
torch.set_default_tensor_type(torch.DoubleTensor) # 設置默認的Tensor類型。
print(torch.tensor([1.2, 3]).type())
- 運行結果!
torch.FloatTensor
torch.DoubleTensor
Process finished with exit code 0
這裏:增強學習 一般使用double類型,其他一般都是使用float。
2.5. 推薦-生成隨機初始化(rand, rand_like,randint)
import torch
import numpy as np
a = torch.rand(3, 3)
print(a)
b = torch.rand_like(a)
print(b)
c = torch.randint(1, 10, [3, 3])
print(c)
- 運行結果:
tensor([[0.4747, 0.2212, 0.2108],
[0.8893, 0.7627, 0.7349],
[0.1388, 0.4769, 0.3684]])
tensor([[0.2752, 0.3832, 0.9476],
[0.2230, 0.5725, 0.9624],
[0.5993, 0.7078, 0.3942]])
tensor([[8, 3, 9],
[9, 8, 3],
[3, 8, 1]])
Process finished with exit code 0
2.6. 正態分佈(randn函數)
import torch
import numpy as np
a = torch.randn(3, 3) # 默認爲(0,1)分佈。均值爲0,方差爲1;
print(a)
# 這裏自定義均值和方差。full生成長度爲10都爲0的向量。方差爲1~0慢慢減少,1, 0.9,..,0.1不包括0;
# 然後改變shape,因此torch.normal這個函數使用起來並不是太直觀。
b = torch.normal(mean=torch.full([10], 0), std=torch.arange(1, 0, -0.1))
print(b)
- 運行結果
tensor([[ 0.0469, -2.1589, -0.9195],
[ 0.8415, 1.5430, 0.6729],
[-0.0043, -0.0103, 0.8269]])
tensor([-0.0540, -0.0626, -0.2210, 1.3035, -0.7214, 0.0067, -0.1359, 0.1929,
-0.1020, 0.0275])
Process finished with exit code 0
2.7. Tensor全部賦值爲指定元素(full函數)
import torch
import numpy as np
a = torch.full([2, 3], 7) # shape [2, 3]全部賦值爲7;
print(a)
b = torch.full([], 7) # 標量
print(b)
c = torch.full([1], 7) # 向量
print(c)
- 運行結果
tensor([[7., 7., 7.],
[7., 7., 7.]])
tensor(7.)
tensor([7.])
Process finished with exit code 0
2.8. arrange/range遞增遞減生成等差數列
import torch
import numpy as np
a = torch.arange(0, 10) # 等差數列,不包含10;和numpy類似。
print(a)
b = torch.arange(0, 10, 2)
print(b)
c = torch.range(0, 10) # 不建議使用的Pytorch
print(c)
- 運行結果
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([0, 2, 4, 6, 8])
/home/zhangkf/johnCodes/Pytorch/py1/one.py:10: UserWarning: torch.range is deprecated in favor of torch.arange and will be removed in 0.5. Note that arange generates values in [start; end), not [start; end].
c = torch.range(0, 10)
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Process finished with exit code 0
2.9. linspace/logspace生成等分
import torch
import numpy as np
a = torch.linspace(0, 10, steps=11) # 這個0, 10都是是包含進來的, 分成4等分。
print(a)
b = torch.logspace(0, 10, steps=11) # 生成10的0次方爲起始值,10的-1次方爲終止值的8個數構成的等比數列
print(b)
- 運行結果
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
tensor([1.0000e+00, 1.0000e+01, 1.0000e+02, 1.0000e+03, 1.0000e+04, 1.0000e+05,
1.0000e+06, 1.0000e+07, 1.0000e+08, 1.0000e+09, 1.0000e+10])
Process finished with exit code 0
這裏: logspace的base參數可以設置爲2,10,e爲底數。
2.10. ones/zeros/eye
import torch
import numpy as np
print(torch.ones(3, 3))
print(torch.zeros(3, 3))
print(torch.eye(2, 3))
- 運行結果
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 0., 0.],
[0., 1., 0.]])
Process finished with exit code 0
這裏: 也有
torch.ones_like(a)
的函數。
2.11. randperm(非常有用隨機打散)
import torch
import numpy as np
aa = torch.randperm(10) # 隨機打散的功能,生成0-10,不包含10, 生成索引。
print(aa)
print('===============================')
# 如下例子
a = torch.rand(3, 3) # 3個人,數學,語文,英語分數(列)
print('數據a:\n', a)
b = torch.rand(3, 2) # 對應的3個人,性別,年齡。
print('數據b:\n', b)
idx = torch.randperm(3) # 生成0~1索引。tensor([0, 1])
print('==========打散之後=============')
print(a[idx]) # 隨機打散數據a。
print(b[idx])
- 運行結果
tensor([1, 0, 3, 2, 5, 4, 7, 6, 9, 8])
===============================
數據a:
tensor([[0.1453, 0.7106, 0.4616],
[0.5674, 0.3137, 0.4973],
[0.0346, 0.3096, 0.6771]])
數據b:
tensor([[0.1258, 0.5768],
[0.9126, 0.4489],
[0.0478, 0.2797]])
==========打散之後=============
tensor([[0.5674, 0.3137, 0.4973],
[0.0346, 0.3096, 0.6771],
[0.1453, 0.7106, 0.4616]])
tensor([[0.9126, 0.4489],
[0.0478, 0.2797],
[0.1258, 0.5768]])
Process finished with exit code 0