pytorch的基础操作

发布于:2024-04-29 ⋅ 阅读:(28) ⋅ 点赞:(0)

目录

一、介绍

二、基础操作

1、张量的基础创建

2、随机创建与转换

3、张量的索引

4、张量的切片

5、张量的维度改变

三、官方手册

中文官方手册,可以查

        


一、介绍

        PyTorch是Torch的Python版本,是由Facebook开源的神经网络框架,专门针对GPU加速的深度神经网络编程。Torch 是一个经典的对多维矩阵数据进行操作的张量(Tensor)库,在机器学习和其他数学密集型应用有广泛应用。与TensorFlow的静态计算图不同,PyTorch的的计算图是动态的,可以根据计算需要实时改变计算图。
        PyTorch的设计追求最少的封装,PyTorch 的设计遵循Tensor— Variable(Autograd)一nn.Module三个由低到高的抽象层次,分别代表高维数组(张量)、自动求导(变量) 和神经网络(层/模块),而且这三个抽象之间联系紧密,可以同时进行修改和操作。

二、基础操作

        PyTorch处理的最基本的操作对象就是张量(Tensor),它表示的就是一个多维矩阵,并有矩阵相关的运算操作PyTorch中张量 ( Tensor) 和NamPy中的数组 非常相似:只是 Tensor 可以在GPU中运算运算,可以进行自动求梯度等操作,在使用时也会经常将PyTorch中的张量和Numpy中的数组相互转换Tensor的数据类型:浮点型和整型,一般常用的就是32位浮点型(torch.Float Tensor),此外还有64位浮点型(torch.DoubleTensor)、32位整型(torch.IntTensor、16位整型(torch Shortlensor) 64位整型(torch.Long Tensor)等

导入包

import torch

1、张量的基础创建

    '''张量的创建'''

    # 简单创建
    a = torch.Tensor([[1, 2], [3, 4]])
    print(a)

    # 2 * 4 全为1的矩阵
    a = torch.ones(2,4)
    print(a)
    # 3 * 3 全为0的矩阵
    a = torch.zeros(3,3)
    print(a)
    # 对角线全为1的矩阵
    a = torch.eye(5,5)
    print(a)
    # 10 ~ 10^2 中随机抽取8个数
    a = torch.logspace(1,2,8)
    print(a)
    # 1到10之间分成8等份
    a = torch.linspace(1,10,8)
    print(a)
    # 1到10之间,步长为2
    a = torch.arange(1,10,2)
    print(a)

2、随机创建与转换

    # 随机生成张量
    a = torch.rand(2,2)
    print(a)

    # 生成的数据服从正态分布 均值默认为0 方差为1
    a = torch.randn(2, 2)
    print(a)

    # 3 * 3 矩阵 值大小为 1 ~ 3
    a = torch.randint(1,3,(3,3))
    print(a)

    # 张量的转化
    a = np.arange(1,13).reshape(3,4)
    print(a)
    # array转化为张量
    b  = torch.from_numpy(a)
    print(b)
    # 张量转化为array
    c = b.numpy()
    print(c)

3、张量的索引

    张量的索引|是从0开始的,比如我们创建一个四维的张量:torch.Tensor(2,3,128,128)
这个张量表示的是2张3通道的128*128大小的彩色图像,第一个维度(维度0))为图像的数量,维度1为图像的通道数,维度2、3为图像的高宽(像素数量)

 '''张量索引'''
    a = torch.Tensor(2, 3, 128, 128)
    print(a.shape)  # 四维张量
    print(a[0].shape)
    print(a[0][0].shape)
    print(a[0][0][0].shape)
    print('_' * 10)

4、张量的切片

        通过上述方法,可以取到张量的某维度全部数据,但是如果我们只想要部分数据如何操作呢,这个我们就可以使用切片
切片语法格式与之前所学的一样,为:tensorlstart:end:step] 

a = torch.Tensor(2, 3, 128, 128)
    print(a[:1, :, :, :].shape)
    print(a[:1, :1, :, :].shape)
    print(a[:1, :1, :64, :64].shape)
    print(a[:1, :1, :1, :1].shape)
    print(a[0:1, :1, :64:2, :64:2].shape)

5、张量的维度改变

     当我们进行具体实验时,我们会发现不同的模型需要对应不同的维度,因此我们需要了解张量的维度变换,可以使用reshape来进行维度的调整,变换后的总元素数量要一致

''' 维度的改变'''
    a = torch.Tensor(2, 3, 128, 128)
    print(a.shape)
    b = a.reshape(2, 3, 128 * 128)
    print(b.shape)
    b = a.reshape(2, 3, -1) # -1是自动计算维度
    print(b.shape)
    c = a.reshape(4, -1)  # 2*3*128*128   /  4
    print(c.shape)
    print('-'*50)

    '''维度交换'''
    a = torch.Tensor(2, 3, 128, 128)  # 交换维度 但是只能交换二个
    print(a.transpose(0, 1).shape)
    a = torch.Tensor(2, 3, 128, 130)  # 交换维度 可以是多个
    print(a.permute(1, 0, 3, 2).shape)

    '''维度扩充'''
    a = torch.Tensor(2, 1, 128, 128)  # 维度扩充
    print(a.expand(2, 3, 128, 128).shape)

三、官方手册

中文官方手册,可以查