张量
创建张量
>>> data = np.ones(3)
>>> data
array([1., 1., 1.])
>>> torch.from_numpy(data)
tensor([1., 1., 1.], dtype=torch.float64)
>>> torch.tensor([1.2,1.3])
tensor([1.2000, 1.3000])
>>> torch.FloatTensor(3)
tensor([1.4013e-45, 0.0000e+00, 0.0000e+00])
生成未初始化的数据
torch.empty(d1,d2,...)
torch.FloatTensor(d1,d2,...)
torch.Tensor(d1,d2,...)
设置默认类型
默认类型为FloatTensor
>>> torch.tensor([1.0,3]).type()
'torch.FloatTensor'
>>> torch.set_default_tensor_type(torch.DoubleTensor)
>>> torch.tensor([1.0,3]).type()
'torch.DoubleTensor'
随机初始化
torch.rand(shape)
>>> torch.rand(2,3)
tensor([[0.5959, 0.1399, 0.4284],
[0.3382, 0.8298, 0.2330]])
>>> a = torch.tensor([[1.0,2.0,3],[4.0,5,6]])
>>> torch.rand_like(a)
tensor([[0.3213, 0.8108, 0.5194],
[0.4343, 0.2518, 0.8131]])
torch.randint(min,max,shape)
>>> torch.randint(1,10,(3,3))
tensor([[2, 1, 9],
[5, 2, 9],
[9, 4, 3]])
randn(shape):服从[0,1]正态分布
常用函数
full
将所有元素赋为一个值
>>> torch.full([2,3],7)
tensor([[7., 7., 7.],
[7., 7., 7.]])
>>> torch.full([],6)
tensor(6.)
arange
生成等差数列
>>> torch.arange(0,10)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
linspace/logspace
生成等分数列
>>> torch.linspace(0,1,steps = 4)
tensor([0.0000, 0.3333, 0.6667, 1.0000])
>>> torch.logspace(0,1,steps = 4)
tensor([ 1.0000, 2.1544, 4.6416, 10.0000])
Ones/Zeros/eye
torch.ones(shape):生成全部为1的矩阵
torch.zeros(shape):生成全部为0的矩阵
torch.eye(shape):生成单位矩阵
randperm
随机打散
>>> torch.randperm(10)
tensor([0, 7, 9, 4, 8, 2, 3, 6, 1, 5])
索引与切片
>>> a = torch.randn(2,3,4)
>>> a
tensor([[[-1.2408, -0.4873, 1.3833, -0.1248],
[-0.3897, -0.7919, -0.3620, 0.4058],
[ 0.1045, -0.6101, 0.0403, -1.6948]],
[[-0.4298, 0.3355, 0.0616, 0.1813],
[ 0.8957, -0.7202, -0.1678, -2.3573],
[-0.3716, -0.1931, -0.5200, 0.2544]]])
>>> a[0,1]
tensor([-0.3897, -0.7919, -0.3620, 0.4058])
>>> a[:2,1:,0:1:4]
tensor([[[-0.3897],
[ 0.1045]],
[[ 0.8957],
[-0.3716]]])
>>> a[...,:2].shape
torch.Size([2, 3, 2])
维度变换
view(shape):变换维度
>>> a=torch.rand(4,1,28,28)
>>> a.view(4,28*28).shape
torch.Size([4, 784])
unsqueeze():插入维度
>>> a.shape
torch.Size([4, 1, 28, 28])
>>> a.unsqueeze(0).shape
torch.Size([1, 4, 1, 28, 28])
>>> a.unsqueeze(-4).shape
torch.Size([4, 1, 1, 28, 28])
squeeze():删减维度
torch.Size([1, 32, 1, 1])
>>> b.squeeze().shape
torch.Size([32])
>>> b.squeeze(3).shape
torch.Size([1, 32, 1])
expand/repeat:扩展维度,只有维度为1的才能扩展
>>> b.shape
torch.Size([1, 32, 1, 1])
>>> b.expand(4,32,14,14).shape
torch.Size([4, 32, 14, 14])
>>> b.shape
torch.Size([1, 32, 1, 1])
>>> b.repeat([4,32,1,1]).shape
torch.Size([4, 1024, 1, 1])
.t():二维矩阵转置
transpose(d1,d2):维度交换,只能交换两个维度
permute():维度交换
>>> a = torch.rand(4,3,28,28)
>>> a.permute(0,2,3,1).shape
torch.Size([4, 28, 28, 3])
>>>
合并与分割
>>> a1=torch.rand(4,3,16,32)
>>> a2=torch.rand(4,3,16,32)
>>> torch.cat([a1,a2],dim=2).shape
torch.Size([4, 3, 32, 32])
>>> torch.stack([a1,a2],dim=2).shape
torch.Size([4, 3, 2, 16, 32])