>>>import torch
>>>a = torch.rand(2, 3)
>>>a.type()
'torch.FloatTensor'
>>>type(a)
<class 'torch.Tensor'>
>>>a = a.cuda()
>>>a.type()
'torch.cuda.FloatTensor'
数据的shape、dimension对应关系:
数据-tensor | shape | dimension |
---|---|---|
2 | () | 0 |
[1, 2] | (2,) | 1 |
[[1, 2, 3], [4, 5, 6]] | (2, 3) | 2 |
shape形状,是数据中括号从外到内元素的个数
dimension维度,可以看做中括号的层数,也可看做shape的长度,即len(shape)
import numpy as np
import torch
a = np.array([1, 2, 3])
torch.from_numpy(a)
a = [2., 2.3]
torch.tersor(a)
torch.empty((2, 3)) #其中(2, 3)是指数据的shape
torch.FloatTensor(3, 1, 28, 28) #其中(3, 1, 28, 28)是指数据的shape
torch.IntTensor(3, 1, 28, 28) #其中(3, 1, 28, 28)是指数据的shape
>>>torch.rand(3, 3)
tensor([[0.0519, 0.4571, 0.4115],
[0.1732, 0.2063, 0.1103],
[0.0497, 0.4221, 0.0586]])
>>>a = torch.rand(3, 3)
>>>torch.rand_like(a)
tensor([[0.2874, 0.0930, 0.7999],
[0.9568, 0.2783, 0.3156],
[0.9964, 0.8501, 0.7862]])
>>>torch.randint(1, 10, (3, 3)) #生成随机数范围[1, 10) shape=(3, 3)
tensor([[1, 2, 8],
[7, 7, 8],
[2, 2, 4]])
>>>torch.randn(3, 3) #N(0, 1) 均值为0 方差为1
tensor([[-1.0693, -1.0430, 0.1060],
[-1.6887, 0.3978, 0.0073],
[-0.3279, 1.9762, 1.7079]])
>>>torch.full((2, 3), 7)
tensor([[7, 7, 7],
[7, 7, 7]])
>>>torch.arange(0, 10)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>torch.linspace(0, 10, steps=4) # 数组起始为0,终止为10, 数组长度为4
tensor([ 0.0000, 3.3333, 6.6667, 10.0000])
>>>torch.linspace(0, 10, steps=11)
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
>>>torch.logspace(0, -1, steps=10) #起始为10^0, 终止为10^-1, 10的指数等差分布,数组长度为10
tensor([1.0000, 0.7743, 0.5995, 0.4642, 0.3594, 0.2783, 0.2154, 0.1668, 0.1292,
0.1000])
>>>torch.logspace(0, -1, base=1, steps=10) #base为底数
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>>torch.ones((3, 3))
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>>torch.zeros((3, 3))
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>>torch.eye(3)
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>>torch.randperm(10)
tensor([8, 2, 3, 0, 7, 1, 5, 4, 6, 9])
# 举例 a表记录了两个人的三门课程成绩,b记录了这两个人的另外两门成绩,现在要将两个人的排序乱序,但表的信息不能乱
>>>a = torch.rand(2, 3)
>>>b = torch.rand(2, 2)
>>>a
tensor([[0.3939, 0.0127, 0.3936],
[0.7625, 0.7905, 0.1113]])
>>>b
tensor([[0.0291, 0.8980],
[0.2153, 0.8673]])
>>>index = torch.randperm(2)
>>>index
tensor([0, 1])
>>>index = torch.randperm(2)
>>>index
tensor([1, 0])
>>>a[index]
tensor([[0.7625, 0.7905, 0.1113],
[0.3939, 0.0127, 0.3936]])
>>>b[index]
tensor([[0.2153, 0.8673],
[0.0291, 0.8980]])