天天看點

pytorch學習筆記一:認識pytorch一、什麼是pytorch二、什麼是torch三、使用pytorch需要了解的幾個概念四、總結

文章目錄

  • 一、什麼是pytorch
  • 二、什麼是torch
  • 三、使用pytorch需要了解的幾個概念
    • 3.1 張量
    • 3.2 torch.autograd
    • 3.3神經網絡
  • 四、總結

一、什麼是pytorch

PyTorch是一個深度學習架構,它是基于Python的科學計算軟體包,可實作兩個廣泛的目的:

1、替代NumPy,以使用GPU和其他加速器的功能。

2、一個自動微分庫,對實作神經網絡很有用

所謂的架構就是别人把底層做好了,應用者隻需要在架構上搭建自己的城堡就行

二、什麼是torch

Torch是一個與Numpy類似的張量(Tensor)操作庫,與Numpy不同的是Torch對GPU支援的很好

三、使用pytorch需要了解的幾個概念

3.1 張量

張量是一種特殊的資料結構,與數組和矩陣非常相似。在PyTorch中,我們使用張量對模型的輸入和輸出以及模型的參數進行編碼。

張量與NumPy的ndarray相似,除了張量可以在GPU或其他專用硬體上運作以加速計算。如果您熟悉ndarrays,則可以輕松使用Tensor API。

import numpy as np
import torch

data = [[1, 2],[3, 4]]
print(data)
print(type(data))
x_data = torch.tensor(data)
print(x_data)
print(x_data.shape)
print(type(x_data))
           

結果如下:

[[1, 2], [3, 4]]
<class 'list'>
tensor([[1, 2],
        [3, 4]])
torch.Size([2, 2])
<class 'torch.Tensor'>
           
import numpy as np
import torch

np_array = np.array(data)
print(np_array)
print(np_array.shape)
print(type(np_array))
x_np = torch.from_numpy(np_array)
print(x_np)
print(x_np.shape)
print(type(x_np))
           

結果如下:

[[1 2]
 [3 4]]
(2, 2)
<class 'numpy.ndarray'>
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
torch.Size([2, 2])
<class 'torch.Tensor'>
           

總結:張量和數組矩陣本質上其實是一個東西,并且用法幾乎沒用差别。PyTorch張量在概念上與numpy數組相同:張量是n維數組,PyTorch提供了許多在這些張量上進行操作的功能。在背景,張量可以跟蹤計算圖和漸變,但它們也可用作科學計算的通用工具。

既然tensor和torch沒有差别,那為什麼還弄出來torch這東西呢?

原因:**Numpy雖然是一個很棒的架構,但是它不能利用GPU來加速其數值計算。**對于現代深度神經網絡,GPU通常會提供50倍或更高的加速比,僅憑numpy不足以實作現代深度學習。

PyTorch張量可以利用GPU加速其數字計算。要在GPU上運作PyTorch Tensor,您隻需要指定正确的裝置即可。

3.2 torch.autograd

torch.autograd是PyTorch的自動差分引擎(即梯度),可為神經網絡訓練提供支援。

torch.autograd主要涉及兩大塊内容,前向傳播和後向傳播

3.3神經網絡

pytorch中使用

torch.nn

軟體包建構神經網絡。可以這麼了解,在pytorch中建構網絡層的時候,隻需要在前加上

torch.nn

即可。如下示例,建構了一個簡單的網絡

import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 3x3 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 3)
        self.conv2 = nn.Conv2d(6, 16, 3)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 6 * 6, 120)  # 6*6 from image dimension
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features


net = Net()
print(net)
           

網絡結果如下:

Net(
  (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
  (fc1): Linear(in_features=576, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
           

torch.nn僅支援小批量。整個torch.nn 程式包僅支援作為小批量樣本的輸入,而不支援單個樣本。

例如,nn.Conv2d将采用的4D張量 。nSamples x nChannels x Height x Width

如果您隻有一個樣本,則隻需使用input.unsqueeze(0)即可添加僞造的批次尺寸。

四、總結

1、torch.Tensor-多元數組,支援autograd操作(如)backward()。還保持張量的梯度。

2、nn.Module-神經網絡子產品。友善的封裝參數的方式,以及将其移動到GPU,導出,加載等的幫助器。

3、nn.Parameter-一種Tensor,将其作為屬性配置設定給時 會自動注冊為參數Module。

4、autograd.Function-實作autograd操作的前向和後向定義。每個Tensor操作都至少建立一個Function節點,該節點連接配接到建立aTensor并對其曆史進行編碼的函數。

繼續閱讀