PyTorch是Python深度学习框架,将数据封装成张量(Tensor)进行计算。
1. 创建基本张量
# 1.根据指定数据创建张量(默认类型—float32)
data11 = torch.tensor(10) # tensor(10)
data12 = torch.tensor(np.random.randn(2,2)) # tensor([[ 0.1702, -0.5733],[ 0.9555, -0.0038]], dtype=torch.float64)
data13 = torch.tensor([[10.,20.],[30.,40.]]) # tensor([[10., 20.],[30., 40.]])
# 2.创建指定形状的张量
data21 = torch.Tensor(2,2) # 创建行列为2,3的张量(随机值) tensor([[0., 0.],[0., 0.]])
data22 = torch.Tensor([[50.,60.]]) # 传递列表,创建指定值的张量 tensor([[50., 60.]])
# 3.创建指定类型的张量
data31 = torch.IntTensor(1,2) # 创建int32,行列为1,2的张量 tensor([[6553710, 3342433]], dtype=torch.int32)
data32 = torch.ShortTensor(1) # 创建int16 tensor([0], dtype=torch.int16)
data33 = torch.LongTensor(2) # 创建int32 tensor([0, 0])
data34 = torch.FloatTensor(1) # 创建float32 tensor([0.])
data35 = torch.DoubleTensor(2) # 创建float64 tensor([1.0570e-307, 8.0110e-307], dtype=torch.float64)
2. 创建线性张量
# 4.创建线性张量
data41 = torch.arange(0,10,2) # (起始值,结束值,步长) tensor([0, 2, 4, 6, 8])
data42 = torch.linspace(0,9,5) # (起始值,结束值,元素个数)—自动计算步长 tensor([0.0000, 2.2500, 4.5000, 6.7500, 9.0000])
3. 创建随机张量
# 5.创建随机张量
rd = torch.random.initial_seed() # 随机数种子,无固定
data51 = torch.randn(2,3) # 行列2,3 随机值(不固定) tensor([[-0.7094, -0.7502, -0.4348], [-0.9200, -0.6664, -2.2633]])
torch.random.manual_seed(10) # 固定随机数种子
data52 = torch.randn(1,2) # 随机值(固定) tensor([[-0.6014, -1.0122]])
4. 创建全0/1张量
# 6.创建全0/1张量
data61 = torch.ones(1,2) # 创建行列为1,2 全为1的张量 tensor([[1., 1.]])
data62 = torch.zeros(1,4) # 创建行列为1,4 全为1的张量 tensor([[0., 0., 0., 0.]])
data63 = torch.full([2,2],10) # 创建行列为2,2 值为10的张量 (维度—元素/列表表示,值)tensor([[10, 10],[10, 10]])
data64 = torch.ones_like(data61) # 创建与data61形状一致的全为1张量 tensor([[1., 1.]])
data65 = torch.zeros_like(data61) # 创建与data61形状一致的全为0张量 tensor([[0., 0.]])
data66 = torch.full_like(data61,5) # 创建与data61形状一致的全为5张量 tensor([[5., 5.]])
5. 张量元素类型转换
# 7.张量元素类型转换
data = torch.full((1, 3), 6) # tensor([[6, 6, 6]]) torch.int64
print(data.dtype) # 查张量类型
data1 = data.type(torch.DoubleTensor) # 返回新的张量,不改变data类型 data—torch.int64 data1—torch.float64
data2 = data.float() # 返回新的张量,不改变data类型 data—torch.int64 data2—torch.float32