• Pytorch(Tensor)-Numpy(ndarrays) API对照表


    pytorchtensornumpyndarray可以说是每一个深度学习工程师必须熟悉的基础工具,而这两个用法相近,但又有部分差异的“轮子”,网上却没有一篇详细的博客进行总结和对比,因此在这里进行记录和整理,希望本文能够帮助各位同学和自己对pytorchnumpy的API加深的理解,并在运用时能做到信手拈来。

    Pytorch API Document:https://pytorch.org/docs/stable/index.html
    Numpy API Document:https://numpy.org/doc/stable/reference/index.html

    0. Tensor和Ndarray有什么区别?

    此处借鉴几位优秀博主的回答:


    接下来进入正式的总结阶段:

    1. 变量基础定义API

    1.1 基础变量

    Tensor(nd)ArraySimilaritiesdifferencesFunction/Example
    torch.tenosr(data, dtype=None, device=None, requires_grad=False)numpy.array(data, dtype=None)都可以对dtype进行定义Tensor可以同时在CPUGPU上,而ndarray只能在CPU上;同时Tensor具有梯度该函数具有的额外参数以下函数均具有,下面不再赘述

    1.2 常用构造变量(ones)

    Tensor(nd)ArraySimilaritiesdifferencesFunction/Example
    torch.ones(size)numpy.ones(shape)这里的sizeshape都是指list/tuplesequence构建全 1 array/Tensor
    torch.zeros(size)numpy.zeros(shape)全0Tensor
    torch.full(size, fill_value)numpy.full(shape, fill_value)都通过fill_value来实现某个数值的填充fill_valuearray/Tensor
    torch.eye(n, m=None)numpy.eye(N, M=None)n都代表默认列数,如果没有m,则行也为m对角线为1,其他为0的单位2D array/Tensor
    Xnumpy.identity(n)对角线为1,行列相等的单位阵
    torch.empty(size)numpy.empty(shape)全为uninitialized data的array/Tensor(即0或者接近0的数)

    1.3 常用构造变量(ones_like)

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    torch.empty_like(input)numpy.empty_like(prototype)inputTensor或者sizeprototypearray like,即所有具有array形式的变量,例如ndarraylisttuple- numpy: a = ([1,2], [4,5]); a = np.array([[1., 2.],[4.,5.]]); np.empty_like(a); - torch: a=torch.empty((2,3)); torch.empty_like(a)
    torch.ones_like(size)numpy.ones_like(shape)
    torch.zeros_like(size)numpy.zeros_like(shape)
    torch.full_like(size, fill_value)numpy.full_like(shape, fill_value)
    • 额外提示:Tensor可以使用Tensor.new_xxxx快速实现额外参数(包括:dtypedevicerequires_grad)全部相同的新变量,例如:
    >>> tensor = torch.tensor((), dtype=torch.int32, device="cuda")
    >>> tensor.new_ones((2, 3))
    tensor([[ 1,  1,  1],
            [ 1,  1,  1]], dtype=torch.int32, device="cuda")
    
    • 1
    • 2
    • 3
    • 4

    2. 基础维度操作API


    2.1 更换维度或者变换shape

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    torch.reshape(input, shape) \ Tensor.reshape(shape)numpy.reshape(a, newshape) \ ndarray.reshape(new_shape)按照给定的新维度变换维度
    torch.resize(input, shape) \ Tensor.resize(shape)numpy.resize(a, newshape) \ ndarray.resize(new_shape)输入参数可以是tuple,也可以是n个int,参考Numpy Example按照给定的新维度变换维度
    torch.transpose(input, dim0, dim1) \ Tensor.transpose(dim0, dim1)numpy.swapaxes(a, axis1, axis2) \ ndarray.swapaxes(axis1, axis2)输入为需要交换的两个维度,参考Torch Example输入为需要交换的两个维度,参考Numpy Example交换某两个维度
    torch.permute(input, dims) \ Tensor.permute(*dims)numpy.transpose(a, axes=None) \ ndarray.transpose(*axes)dims:最终tensor的shape,可以是tuple,也可以是n个int,参考Torch Exampleaxes:可以是tuple,也可以是n个int,若未指定,则反向交换维度;参考Numpy Example交换某两个维度

    2.2 增加或减少某一维

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    torch.squeeze(input, dim=None) \ tensor.squeeze(dim=None)numpy.squeeze(a, axis=None) \ ndarray.squeeze(axis=None)去除某一为1的维度
    torch.unsqueeze(input, dim=None) \ tensor.unsqueeze(dim=None)numpy.unsqueeze(a, axis=None) \ ndarray.unsqueeze(axis=None)指定增加某一维度
    X numpy.expand_dims(a, axis)指定增加某一维度

    2.3 合并多个TensorNdarray

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    tensor.stack(tensors, dim=0)numpy.stack(arrays, axis=0)tensors:用list装起来的tensorarrays :用list装起来的array_like(array, list)的变量在指定维度新建一维,合并tensor/ array
    torch.cat(tensors, dim=0) \ torch.concatenate(tensors, dim=None)numpy.concatenate((a1, a2, ...), axis=0在指定维度直接合并tensor/ array
    • 其他类似的更多函数:
      • numpy.hstacknumpy.vstacknumpy.dstack

    2.4 分离多个TensorNdarray

    • 其他类似的更多函数:
      • numpynumpy.splitnumpy.hsplitnumpy.vsplitnumpy.dsplit

    3. 基础运算API

    待更…

    4. 操作矩阵API

    4.1 roll

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    torch.roll(input, shifts, dims=None)numpy.roll(a, shift, axis=None)shiftdims可以是int或者list/tuple参数与Pytorch相同在指定维度滚动shifts步,移位多出来的部分补齐到前边,类似于一个闭合圆,不断循环。
    >>> x = np.arange(10)
    >>> np.roll(x, 2)
    array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
    >>> np.roll(x, -2)
    array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.2 flip

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    torch.flip(input, dims)numpy.flip(a, axis)dimslist/tuple参数与Pytorch相同在指定维度反转数据

    4.3 repeat

    Tensor(nd)ArrayTensor ParamsNdarray ParamsFunction/Example
    Tensor.repeat(sizes)numpy.repeat(a, axis)sizeslist/tuple,所有维度需要重复的次数,如果不变则为0a为操作对象,axis为需要操作的维度在指定维度复制数据
  • 相关阅读:
    Effective C++改善程序与设计的55个具体做法 6. 继承与面向对象设计
    HTML5中自定义数据属性:data-*的使用
    星火认知大模型Spark3.5 api调用 #AI夏令营 #Datawhale #夏令营
    阿里云函数计算 1024云上见 AIGC小说创作大赛:如何搭建自定义的阿里通义千问
    JVM第六讲:JVM 基础 - Java 内存模型引入
    【python】如何注释
    Postman抓包网页请求
    爽爆!阿里腾讯都在传的MySQL精华手册,GitHub标星89K
    QT 自定义抽屉式窗口,上层覆盖下层界面,下层布局不改变
    京东大数据:2023年Q3美妆行业数据分析报告
  • 原文地址:https://blog.csdn.net/qq_45779334/article/details/127698392