PyTorch入门(一):什么是PyTorch

pytorch官方网站
PyTorch是一个基于Python的科学计算软件包:numpy的替代品,可使用强大的GPU功能;一个深度学习平台,具有最大的灵活性和最快的速度。

  1. 张量(Tensors)
    与numpy的ndarrays类似,用于GPU加速计算。

    一个未初始化的5行3列矩阵

    a = torch.empty(5,3)
    print(a)
    

    输出为
    在这里插入图片描述
    一个随机初始化的5行3列矩阵

    a = torch.rand(5, 3)
    print(a)
    

    输出为
    在这里插入图片描述
    一个5行3列,值均为0的矩阵,类型为long

    a = torch.zeros(5, 3, dtype=torch.long)
    print(a)
    

    输出为在这里插入图片描述
    一个直接给定数值的张量

    a = torch.tensor([5.5, 3])
    print(a)
    

    输出为
    在这里插入图片描述
    根据现有的张量创建张量。 这些方法将重用输入张量的属性

    a = a.new_ones(5, 3, dtype=torch.double)
    print(a)
    
    a = torch.randn_like(a, dtype=torch.float)
    print(a) 
    

    输出为
    在这里插入图片描述
    在这里插入图片描述

    print(a.size())
    

    输出为
    在这里插入图片描述

    torch.size()是一个元祖,支持所有元祖操作

  2. 操作(operations)
    操作有多种语法,以加法为例。

    A.
    b= torch.rand(5, 3)
    print(a + b)
    
    B.
    print(torch.add(a,b))
    
    C.提供一个输出张量作为参数
    result = torch.empty(5, 3)
    torch.add(x, y, out=result)
    print(result)
    
    D.
    y.add_(x)
    print(y)
    

    输出均为
    在这里插入图片描述
    任何改变一个张量位置的操作都是用_固定的,即y.add_(x)会改变y的值

    同样可以对张量使用标准numpy操作。

    如果想要更改张量的尺寸(size),使用torch.view

    x = torch.randn(4, 4)
    y = x.view(16)
    z = x.view(-1, 8) 
    print(x.size(), y.size(), z.size())
    

    输出为
    在这里插入图片描述
    通过.item()可以将张量元素的值返回为python数字

    x = torch.randn(1)
    print(x)
    print(x.item())
    

    输出为
    在这里插入图片描述
    Numpy bridge
    Torch Tensor和NumPy阵列将共享其底层内存位置,更改一个将改变另一个

    将tensor转为numpy

    a = torch.ones(5)
    print(a)
    
    b = a.numpy()
    print(b)
    
    a.add_(1)
    print(a)
    print(b)
    

    输出为
    在这里插入图片描述
    将numpy转为tensor 在这里插入图片描述

  3. CUDA Tensors
    通过.to方法移动Tensors
    使用torch.device将Tensors移入或移出GPU

    x = torch.rand(3,2)
    if torch.cuda.is_available():
    device = torch.device("cuda")        
    y = torch.ones_like(x, device=device)  
    x = x.to(device) 
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))  
    

    输出为

猜你喜欢

转载自blog.csdn.net/weixin_40543841/article/details/86526106