在PyTorch中,有多种方法可以创建张量。以下是一些常用的方法:
- 使用
torch.Tensor()
构造函数创建张量:
import torch # 创建一个2x3的浮点型张量,初始值为0 tensor1 = torch.Tensor(2, 3) print(tensor1) # 创建一个3x4的整数型张量,初始值为0 tensor2 = torch.Tensor(3, 4, dtype=torch.int) print(tensor2)
- 使用
torch.zeros()
、torch.ones()
和torch.rand()
函数创建全零、全一和随机张量:
import torch # 创建一个2x3的全零张量 tensor_zeros = torch.zeros(2, 3) print(tensor_zeros) # 创建一个2x3的全一张量 tensor_ones = torch.ones(2, 3) print(tensor_ones) # 创建一个2x3的随机张量,数值范围在0到1之间 tensor_rand = torch.rand(2, 3) print(tensor_rand)
- 使用
torch.arange()
和torch.linspace()
函数创建等差和等比数列张量:
import torch # 创建一个从0开始,步长为1的2x3等差数列张量 tensor_arange = torch.arange(2).repeat(3, 1) print(tensor_arange) # 创建一个从0开始,到1之间,共5个元素的2x3等比数列张量 tensor_linspace = torch.linspace(0, 1, 5).view(2, 3) print(tensor_linspace)
- 使用
torch.eye()
函数创建单位矩阵张量:
import torch # 创建一个3x3的单位矩阵张量 tensor_eye = torch.eye(3) print(tensor_eye)
- 使用
torch.tensor()
函数从现有数据创建张量:
import torch # 从列表创建一个2x3的张量 data = https://www.yisu.com/ask/[[1, 2, 3], [4, 5, 6]]>以上就是PyTorch中创建张量的一些常用方法。