torch用法--张量操作

发布时间 2023-11-23 22:07:42作者: 黑逍逍

创建张量:

  • torch.tensor(data): 从数据中创建张量。用列表创建,numpy创建
  • 维度只看[ ]
# 一维张量
data_1d = [1, 2, 3]
tensor_1d = torch.tensor(data_1d)
# 结果
tensor([1, 2, 3])

  

# 二维张量
data_2d = [[1, 2, 3], [4, 5, 6],[4, 5, 6]]
tensor_2d = torch.tensor(data_2d)
#结果
tensor([[1, 2, 3],
[4, 5, 6]
[4, 5, 6]])
# 但是形状是
torch.Size([3, 3])

  

# 三维张量
tensor_3d = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
                         [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]])
# 结果
tensor([[[ 1,  2,  3,  4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],

[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])

  

  • torch.zeros(shape): 创建指定形状的全零张量。
  • torch.ones(shape): 创建指定形状的全一张量。
  • torch.randn(shape): 创建指定形状的随机张量。

 

张量操作:

  • tensor.size(): 返回张量的大小。形状的大小,几行几列
  • tensor.view(shape): 改变张量的形状。
# 创建一个4x3的矩阵(2维tensor)
tensor_original = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

# 结果
tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

# 使用view改变形状为3x4
tensor_reshaped = tensor_original.view(3, 4)
# 结果
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]])

  

  • torch.cat(tensors, dim): 沿指定维度拼接张量。
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])

# dim=0 表示沿着第一个维度(行的方向)进行连接。
concatenated_tensor = torch.cat([tensor1, tensor2], dim=0)
tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

# dim=1 表示沿着第二个维度(列的方向)进行连接。
concatenated_tensor = torch.cat([tensor1, tensor2], dim=1)
tensor([[ 1, 2, 3, 7, 8, 9],
[ 4, 5, 6, 10, 11, 12]])

  

  • tensor.item(): 获取张量中的单个元素的数值

 

数学运算:

a = torch.tensor([[1, 2, 3], [4, 5, 6]])

b = torch.tensor([[7, 8, 9], [10, 11, 12]])

tensor([[1, 2, 3],
        [4, 5, 6]])

tensor([[ 7,  8,  9],
        [10, 11, 12]])
  • torch.add(tensor1, tensor2): 张量相加。
result = torch.add(a, b)
tensor([[ 8, 10, 12],
        [14, 16, 18]])

  

  • torch.sub(tensor1, tensor2): 张量相减。
  • torch.mul(tensor1, tensor2): 张量相乘。
torch.mul(a,b)
tensor([[ 7, 16, 27],
        [40, 55, 72]])

  

  • torch.div(tensor1, tensor2): 张量相除

自动求导:

  • tensor.requires_grad_(True): 启用梯度跟踪。
  • tensor.backward(): 计算梯度。
  • tensor.grad: 获取计算得到的梯度。