NumPy和Torch对比

  1. NumPy中ndarray和Torch中tensor的相互转化
    1. # NumPy中ndarray和Torch中tensor的相互转化
    2. numpyData = numpy.arange(6).reshape(2, 3)
    3. # ndarray到tensor
    4. torchData = torch.from_numpy(numpyData)
    5. # tensor到ndarray
    6. tensor2array = torchData.numpy()
    7. print(
    8. "\nnumpy array:\n", numpyData,
    9. "\ntorch tensor:\n", torchData,
    10. "\ntensor to array\n", tensor2array
    11. )


运行结果

  1. numpy array:
  2. [[0 1 2]
  3. [3 4 5]]
  4. torch tensor:
  5. tensor([[0, 1, 2],
  6. [3, 4, 5]])
  7. tensor to array
  8. [[0 1 2]
  9. [3 4 5]]
  1. 数学运算
  • 绝对值
    1. # 绝对值计算abs
    2. data = [-1, -2, 1, 2]
    3. tensor = torch.FloatTensor(data) # 32位
    4. print(
    5. '\nabs',
    6. '\nnumpy:\n', numpy.abs(data),
    7. '\ntorch:\n', torch.abs(tensor)
    8. )


运行结果

  1. abs
  2. numpy:
  3. [1 2 1 2]
  4. torch:
  5. tensor([1., 2., 1., 2.])
  • sin
    1. # 三角函数sin
    2. print(
    3. '\nsin',
    4. '\nnumpy:\n', numpy.sin(data),
    5. '\ntorch:\n', torch.sin(tensor)
    6. )


运行结果

  1. sin
  2. numpy:
  3. [-0.84147098 -0.90929743 0.84147098 0.90929743]
  4. torch:
  5. tensor([-0.8415, -0.9093, 0.8415, 0.9093])
  • 平均值
    1. # 平均值
    2. print(
    3. '\nmean',
    4. '\nnumpy:\n', numpy.mean(data),
    5. '\ntorch:\n', torch.mean(tensor)
    6. )


运行结果

  1. mean
  2. numpy:
  3. 0.0
  4. torch:
  5. tensor(0.)
  1. 矩阵乘法
    1. # 矩阵乘法
    2. data = [[1, 2],
    3. [3, 4]]
    4. tensor = torch.FloatTensor(data)
    5. print(
    6. '\n叉乘',
    7. '\nnumpy:\n', numpy.matmul(data, data),
    8. '\ntorch:\n', torch.mm(tensor, tensor)
    9. )
    10. print(
    11. '\n点乘',
    12. '\nnumpy:\n', numpy.multiply(data, data),
    13. '\ntorch:\n', torch.mul(tensor, tensor)
    14. )


运行结果

  1. 叉乘
  2. numpy:
  3. [[ 7 10]
  4. [15 22]]
  5. torch:
  6. tensor([[ 7., 10.],
  7. [15., 22.]])
  8. 点乘
  9. numpy:
  10. [[ 1 4]
  11. [ 9 16]]
  12. torch:
  13. tensor([[ 1., 4.],
  14. [ 9., 16.]])