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