• torch.Tensor和numpy.ndarray


    1. torch.Tensor和numpy.ndarray相互转换

    import torch
    import numpy as np
    # <class 'numpy.ndarray'>
    np_data = np.arange(6).reshape((2,3))
    # <class 'torch.Tensor'>
    torch_data = torch.from_numpy(np_data)
    # <class 'numpy.ndarray'>
    tensor2array = torch_data.numpy()
    print('numpy array:
    ',np_data,type(np_data),
          '
    torch tensor:
    ',torch_data,type(torch_data),
          '
    tensor to array:
    ',tensor2array,type(tensor2array))
    # numpy array:
    # [[0 1 2]
    # [3 4 5]] <class 'numpy.ndarray'>
    # torch tensor:
    # tensor([[0, 1, 2],
    # [3, 4, 5]]) <class 'torch.Tensor'>
    # tensor to array:
    # [[0 1 2]
    # [3 4 5]] <class 'numpy.ndarray'>

    torch.Tensor:是一个包含了一种数据类型元素的多维矩阵,缺省为torch.FloatTensor
    2. torch.Tensor和numpy.ndarray一些简单操作,如均值,绝对值,sin,log等
    data = [-1,-2,1,2]
    tensor_default = torch.Tensor(data)
    tensor = torch.FloatTensor(data)
    print('tensor default type:
    ',tensor_default,
          '
    tensor FloatTensor type:
    ',tensor,
          '
    abs:',
          '
    numpy:',np.abs(data),
          '
    torch:',torch.abs(tensor),
          '
    sin:',
          '
    numpy:',np.sin(data),
          '
    torch:',torch.sin(tensor),
          '
    mean:',
          '
    numpy:',np.mean(data),
          '
    torch:',torch.mean(tensor),)
    # tensor default type:
    # tensor([-1., -2., 1., 2.])
    # tensor FloatTensor type:
    # tensor([-1., -2., 1., 2.])
    # abs:
    # numpy: [1 2 1 2]
    # torch: tensor([1., 2., 1., 2.])
    # sin:
    # numpy: [-0.84147098 -0.90929743 0.84147098 0.90929743]
    # torch: tensor([-0.8415, -0.9093, 0.8415, 0.9093])
    # mean:
    # numpy: 0.0
    # torch: tensor(0.)

    3. 矩阵乘法(正确的做法)
    data = [[1,2], [3,4]]
    tensor = torch.FloatTensor(data)
    print(
        '
    matrix multiplication (matmul):',
        '
    numpy:
    ', np.matmul(data, data),     # [[7, 10], [15, 22]]
        '
    torch:
    ', torch.mm(tensor, tensor))  # [[7, 10], [15, 22]]
    # matrix multiplication (matmul):
    # numpy:
    # [[ 7 10]
    # [15 22]]
    # torch:
    # tensor([[ 7., 10.],
    # [15., 22.]])
  • 相关阅读:
    一个简单的window.onscroll实例
    vue 自定义组件使用v-model
    vue开发后台管理系统有感
    cube打包后css顺序错误
    app嵌套的vue项目更新后,页面没有更新
    vue打包后css背景图片地址找不到
    git取消操作命令
    cube-ui indexList的正确使用
    首次db查询时延迟明显高于后面几次。
    git中的merge与rebase
  • 原文地址:https://www.cnblogs.com/jeshy/p/11183632.html
Copyright © 2020-2023  润新知