zoukankan      html  css  js  c++  java
  • 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.]])
  • 相关阅读:
    【XXE学习】XML外部实体注入
    记一次解密wireshark抓取的冰蝎通信流量
    weblogicSSRF漏洞复现
    解决docker删除加载失败的镜像报错
    【vulapps】Sturcts2 S2-037RCE漏洞复现
    【XSS-labs】level 16-20
    解决docker-compose下载过慢
    【XSS-labs】Level 11-15
    【XSS-labs】level 6-10
    [PHP]用PHP自己写一个基于zoomeye的api(偷懒必备quq)
  • 原文地址:https://www.cnblogs.com/jeshy/p/11183632.html
Copyright © 2011-2022 走看看