pytorch的优势

  • torch是动态计算图系统,不同于tensorflow 1.0的静态计算图(先构建好图再计算),torch是边构建图边计算,因此更加易用。
  • torch的代码风格更加python-style,api也更稳定,因此相比tf更加便于上手。

基本数据结构

tensor

使用方法

  • 构造tensor
    1
    2
    3
    4
    5
    6
    # 法1:调用函数
    # 构造shape为(3,2)的全0tensor
    tensor1 = torch.zeros(3,2)

    # 法2:用python list构造tensor
    tensor2 = torch.tensor([[1.0, 4.0], [2.0, 1.0], [3.0, 5.0]])

理论原理

  • pytorch的基本数据结构是tensor,可看作是多维数组。
  • pytorch中的tensor和numpy中的ndarry可以方便地切换,此外tensor在ndarray的基础上加入了分布式计算、计算图跟踪等功能,使其更适用于构建深度学习系统。

    tensor 和 python list

  • tensor相比python list的优势:1)list中的每一个元素都是一个单独的存储对象(因为list的存储对象可以是任意类型的),没有存储优化,这在大数据的情况下会占用大量存储;2)并没有针对list的数学运算的优化,比如向量加法、点乘等;3)python解释器非常慢。
    因此目前的机器学习框架都会重新实现数据存储的基本单元(如tensor、ndarray等),在底层优化数学运算的效率。

tensor的底层存储

  • tensor和python list底层存储的差异:python list中的每个元素都是一个特定的python object,离散地占有内存;torch tensor中的元素则直接是C语言的数值类型(如4 bytes 的float类型),所有tensor中的元素连续地占有一块内存,因此存储更为高效。
  • tensor的存储机制:tensor的底层存储是torch.Storge,相当于一维的数组,存储了tensor的数据内容(按维度增加的顺序)。而tensor只是指向了torch.Storge中数据的特定部分,类似于指针,不同的tensor也可同时指向一个torch.Storge数据(因此内存是共享的,不会新增存储空间)。
    Eg.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    # In:
    points = torch.tensor([[1.0, 4.0], [2.0, 1.0], [3.0, 5.0]])
    points.storage()
    # Out:
    1.0
    4.0
    2.0
    1.0
    3.0
    5.0
    [torch.FloatStorage of size 6]

    # 改变Storage的值也会改变指向其的tensor的值
    # In[20]:
    points = torch.tensor([[1.0, 4.0], [2.0, 1.0], [3.0, 5.0]])
    points_storage = points.storage()
    points_storage[0] = 2.0
    points
    # Out[20]:
    tensor([[2., 4.],
    [2., 1.],
    [3., 5.]])
  • tensor和storage的对应关系
    tensor和storage的对应关系
    tensor有三个属性决定了其如何引用storage中的数据,分别是:
    size:tensor的shape;
    storage_offset:决定了tensor中的数据(0, 0)是从storage中哪个位置开始的;
    stride:决定了tensor各维度数据对应在storage中的步长。


Post Date: 2020-01-17

版权声明: 本文为原创文章,转载请注明出处