zoukankan      html  css  js  c++  java
  • Torch或Numpy

    1.什么是Numpy
    Numpy系统是Python的一种开源的数值计算扩展,用python实现的科学计算包。这种工具可用来存储和处理大型矩阵,包括强大的N维数组对象Array,比较成熟的函数库等。numpy和稀疏矩阵运算包scipy配合使用更加方便。

    2.用Numpy还是Torch
    Torch自称为神经网络界的Numpy,它能将torch产生的tensor放在GPU中加速运算,就想Numpy会把array放在CPU中加速运算。所以在神经网络中,用Torch的tensor形式更优。

    但是为了减少用户的学习成本,Torch对Numpy实现了很好的兼容。可以用如下形式在numpy array和torch tensor之间自由转换。

    import torch
    import numpy as np

    np_data = np.arange(6).reshape((2, 3))
    torch_data = torch.from_numpy(np_data)
    tensor2array = torch_data.numpy()
    print(
    ' numpy array:', np_data, # [[0 1 2], [3 4 5]]
    ' torch tensor:', torch_data, # 0 1 2 3 4 5 [torch.LongTensor of size 2x3]
    ' tensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
    )

    3.Torch中的数学运算

    torch中的tensor运算和numpy的array运算很相似,具体参看下面的代码:

    # abs 绝对值计算
    data = [-1, -2, 1, 2]
    tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
    print(
    ' abs',
    ' numpy: ', np.abs(data), # [1 2 1 2]
    ' torch: ', torch.abs(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) # [-0.8415 -0.9093 0.8415 0.9093]
    )

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

    numpy和torch的矩阵乘法还是有点不同的,下面将对其区别进行展示:

    # matrix multiplication 矩阵点乘
    data = [[1,2], [3,4]]
    tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
    # correct method
    print(
    ' matrix multiplication (matmul)',
    ' numpy: ', np.matmul(data, data), # [[7, 10], [15, 22]]
    ' torch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]
    )

    # !!!! 下面是错误的方法 !!!!
    # 注意这里要转换成array,因为data原来是list对象,其没有.dot操作
    data = np.array(data)
    print(
    ' matrix multiplication (dot)',
    ' numpy: ', data.dot(data), # [[7, 10], [15, 22]] 在numpy 中可行
    ' torch: ', tensor.dot(tensor) # torch 会转换成 [1,2,3,4].dot([1,2,3,4]) = 30.0
    )

  • 相关阅读:
    Diverse Garland
    Basketball Exercise
    Quasi Binary
    Vacations
    Given Length and Sum of Digits...
    三大集合框架之map
    三大集合框架之Set
    JDBC操作数据库的基本步骤:
    java面试之----堆(heap)、栈(stack)和方法区(method)
    JSP九大隐式对象
  • 原文地址:https://www.cnblogs.com/pythonClub/p/10412937.html
Copyright © 2011-2022 走看看