zoukankan      html  css  js  c++  java
  • pytorch 1 torch_numpy, 对比

    import torch
    import numpy as np
    

    details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations

    convert numpy to tensor or vise versa

    # convert numpy to tensor or vise versa
    np_data = np.arange(6).reshape((2, 3)) 
    torch_data = torch.from_numpy(np_data)  # np转成torch
    tensor2array = torch_data.numpy()       # torch转成np
    print(
        '
    numpy array:', np_data,           # [[0 1 2] [3 4 5]]
        '
    torch tensor:', torch_data,       # tensor([[0, 1, 2], [3, 4, 5]])
        '
    tensor to array:', tensor2array,  # [[0 1 2], [3 4 5]]
    )
    

    abs 绝对值

    # abs
    data = [-1, -2, 1, 2]
    tensor = torch.FloatTensor(data)  # 32-bit floating point
    print(
        '
    abs',
        '
    numpy: ', np.abs(data),          # [1 2 1 2]
        '
    torch: ', torch.abs(tensor)      # tensor([1., 2., 1., 2.])
    )
    

    sin 正弦值

    # sin
    print(
        '
    sin',
        '
    numpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
        '
    torch: ', torch.sin(tensor)  # tensor([-0.8415, -0.9093,  0.8415,  0.9093])
    )
    

    mean 均值

    # mean 
    print(
        '
    mean',
        '
    numpy: ', np.mean(data),         # 0.0
        '
    torch: ', torch.mean(tensor)     #  tensor(0.)
    )
    
    

    matrix multiplication 矩阵乘法

    # matrix multiplication
    data = [[1, 2], [3, 4]]
    tensor = torch.FloatTensor(data)  # 32-bit floating point
    # correct method
    print(
        '
    matrix multiplication (matmul)',
        '
    numpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
        '
    torch: ', torch.mm(tensor, tensor)   # tensor([[ 7., 10.], [15., 22.]])
    )
    

    incorrect method 不正确的方法

    # incorrect method
    data = np.array(data)
    print(
        '
    matrix multiplication (dot)',
        '
    numpy: ', data.dot(data),        # [[7, 10], [15, 22]]
        '
    torch: ', tensor.dot(tensor)     # this will convert tensor to [1,2,3,4], you'll get 30.0, RuntimeError: dot: Expected 1-D argument self, but got 2-D
    )
  • 相关阅读:
    python爬虫实战(1)--爬取糗事百科
    python爬虫(5)--正则表达式
    python爬虫(4)--Cookie的使用
    python爬虫(3)--异常处理
    python爬虫(2)--Urllib库的高级用法
    EQ2008 LED控制卡二次开发
    C# 遍历对象属性取值赋值
    BootStrap Table
    MongoDB 操作
    SQL Server 2008(R2) 数据库使用外网IP实例连接服务器
  • 原文地址:https://www.cnblogs.com/yangzhaonan/p/10439416.html
Copyright © 2011-2022 走看看