# 创建一个标量(0维张量)
scalar_tensor = torch.tensor(3.14)
# 创建一个向量(1维张量)
vector_tensor = torch.tensor([1, 2, 3])
# 创建一个矩阵(2维张量)
matrix_tensor = torch.tensor([[1, 2], [3, 4]])
# 创建一个3维张量
tensor_3d = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
zero_tensor = torch.zeros(3, 4) # 3行4列的全零矩阵
ones_tensor = torch.ones(2, 3) # 2行3列的全一矩阵
constant_tensor = torch.full((2, 2), 7) # 2行2列的常数填充矩阵,值为7
identity_matrix = torch.eye(3) # 3阶单位矩阵
range_tensor = torch.arange(0, 10, 2) # 从0开始,步长为2,直到小于10
rand_tensor = torch.rand(2, 3) # 2行3列的均匀分布随机矩阵
randn_tensor = torch.randn(3, 3) # 3行3列的正态分布随机矩阵
x = torch.rand(2, 3)
print(x.size()) # 输出: torch.Size([2, 3])
x = torch.rand(2, 3, dtype=torch.float)
print(x.dtype) # 输出: torch.float32
if torch.cuda.is_available():
device = torch.device("cuda") # GPU 设备
else:
device = torch.device("cpu") # CPU 设备
x = x.to(device)
t = torch.randn(3,3)
t1 = torch.randn_like(t)
t = torch.rand(3, 4, 5)
t.nelement() # 返回数量
t.size() # 返回尺寸,元组
t.shape # 返回形状,元组
t.size(2) # 返回指定维度大小
t.view(12, 5)
t.view(-1, 6).shape
t.view(-1, 6).transpose(1, 0).shape
张量的索引和切片和列表基本是一样的,有步长、起点、终点等。例如:
t[0,0,2] t[:,1,1] t>0 t[t > 0]
# 加法运算
add_res = x + y
# 减法运算
sub_res = x - y
# 乘法运算
mul_res = x * y
# 除法运算
div_res = x / y
# 加法运算
add_res = torch.add(x, y)
# 减法运算
sub_res = torch.subtract(x, y)
# 乘法运算
mul_res = torch.mul(x, y)
# 除法运算
div_res = torch.div(x, y)
x = torch.randn(3, 4)
y = x.transpose(0, 1)
下面是对张量操作的总结,不含代码,要用再查:
与·numpy的互操作:
# 从张量points得到一个numpy数组
points_np = points.numpy()
# 从numpy得到一个pytorch张量
points = torch.from_numpy(points_np)