本章正式開始使用pytorch的接口來實現對應的numpy的學習的過程,來學習模型的實現,我們會介紹numpy是如何學習的,以及我們如何一步步的通過torch的接口來實現簡單化的過程,優雅的展示我們的代碼,已經我們的代碼完成的事情
numpy的線性回歸
在此之前,先看看現在的numpy實現的學習的過程是什么樣的
#引入計算模塊
import numpy as np
from sklearn.linear_model import LinearRegressionimport torch
import torch.optim as optim
import torch.nn as nn
from torchviz import make_dot用真實的數據來生成對應的分布點的數據
true_b = 1
true_w = 2
N = 100# Data Generation
np.random.seed(42)
x = np.random.rand(N, 1)
epsilon = (.1 * np.random.randn(N, 1))
y = true_b + true_w * x + epsilon
np.rand# Shuffles the indices
idx = np.arange(N)
np.random.shuffle(idx)# Uses first 80 random indices for train
train_idx = idx[:int(N*.8)]
# Uses the remaining indices for validation
val_idx = idx[int(N*.8):]# Generates train and validation sets
x_train, y_train = x[train_idx], y[train_idx]
x_val, y_val = x[val_idx], y[val_idx]np.random.seed(42)
b = np.random.randn(1)
w = np.random.randn(1)for _ in range(1000):# Step 1 - Computes our model's predicted output - forward passyhat = b + w * x_train# Step 2 - Computing the loss# We are using ALL data points, so this is BATCH gradient# descent. How wrong is our model? That's the error!error = (yhat - y_train)# It is a regression, so it computes mean squared error (MSE)loss = (error ** 2).mean()# Step 3 - Computes gradients for both "b" and "w" parametersb_grad = 2 * error.mean()w_grad = 2 * (x_train * error).mean()# Sets learning rate - this is "eta" ~ the "n" like Greek letterlr = 0.1# Step 4 - Updates parameters using gradients and # the learning rateb = b - lr * b_gradw = w - lr * w_grad#驗證,通過線性的模型直接學習
linr = LinearRegression()
linr.fit(x_train, y_train)
如上一章所說,我們的5個步驟,就是準備數據,前向傳遞,計算損失,計算梯度,更新參數,循環往復
pytorch的取代
張量(通常指3維)但是這里除了標量全部都是張量,為了簡化。
#如下是創建張量的例子
scalar = torch.tensor(3.14159) #張量
vector = torch.tensor([1, 2, 3]) #一維
matrix = torch.ones((2, 3), dtype=torch.float) #二維
tensor = torch.randn((2, 3, 4), dtype=torch.float) #三維
獲取到張量的shape
shape將會是我們以后將會長期用到的東西
print(tensor.size(), tensor.shape)
torch.Size([2, 3, 4]) torch.Size([2, 3, 4])
view
我們可以使用view的接口來改變一個張量的shape,注意view并不會創建新的張量。
# We get a tensor with a different shape but it still is the SAME tensor
same_matrix = matrix.view(1, 6)
# If we change one of its elements...
same_matrix[0, 1] = 2.
創建新的tensor
使用這個可以使用new_tensor和clone
# We can use "new_tensor" method to REALLY copy it into a new one
different_matrix = matrix.new_tensor(matrix.view(1, 6))
# Now, if we change one of its elements...
different_matrix[0, 1] = 3.
使用clone.detach,為什么要用detach(涉及到后面的數據存放和計算的內容)
another_matrix = matrix.view(1, 6).clone().detach()
加載數據、設備、CUDA
我們需要從numpy的數據轉成tensor張量
x_train_tensor = torch.as_tensor(x_train)
x_train.dtype, x_train_tensor.dtype
注意,這里變成了torch的張量,但是這里是還是共享的原始的內存,換句話說,改了還是會一起改
(dtype('float64'), torch.float64)
cuda的數據
cuda就是要使用GPU來存儲和運算的數據,我們需要手動的將其放到GPU的內存中,用于加速計算的過程
#判斷是否有GPU的數據可以使用的接口,如果存在那么設置device為GPU,否則CPU
device = 'cuda' if torch.cuda.is_available() else 'cpu'
#可以獲取GPU的數量
n_cudas = torch.cudsa.device_count()
for i in range(n_cuda):print(torch.cuda.get_device_naem(i))
我的機器上的輸出的結果
NVIDIA GeForce RTX 2060
將數據發送到GPU上
gpu_tensor = torch.as_tensor(x_train).to(device)
gpu_tensor[0]
輸出
torch.cuda.FloatTensor
如果發送到了GPU上的數據,需要重新變成numpy的數組,需要使用CPU的變量
back_to_numpy = x_train_tensor.cpu().numpy()
創建參數,并且需要梯度計算
為什么要使用torch,很多的時候在于可以自行進行梯度計算,也可以使用到很多pytorch的使用的接口和用法
# 創建一個隨機1以內的參數,并且需要梯度,類型是float
b = torch.randn(1, requires_grad=True, dtype=torch.float)
w = torch.randn(1, requires_grad=True, dtype=torch.float)
print(b, w)
創建數據并且發送到GPU,但是需要注意的是,這樣會丟失梯度,因為這個是CPU的數據需要梯度,發送到GPU后又是新的數據,
b = torch.randn(1, requires_grad=True, dtype=torch.float).to(device)
w = torch.randn(1, requires_grad=True, dtype=torch.float).to(device)
好的方法是直接在GPU上創建變量
b = torch.randn(1, requires_grad=True, dtype=torch.float,device = device)
w = torch.randn(1, requires_grad=True, dtype=torch.float),device = device)
Autograd
自動求解梯度
backward
我們可以通過backward直接計算和進行backward的實現,注意b,w是我們創建的參數(需要梯度的那種)
# Step 1 - Computes our model's predicted output - forward pass
yhat = b + w * x_train_tensor# Step 2 - Computes the loss
# We are using ALL data points, so this is BATCH gradient descent
# How wrong is our model? That's the error!
error = (yhat - y_train_tensor)
# It is a regression, so it computes mean squared error (MSE)
loss = (error ** 2).mean()# Step 3 - Computes gradients for both "b" and "w" parameters
# No more manual computation of gradients!
# b_grad = 2 * error.mean()
# w_grad = 2 * (x_tensor * error).mean()
loss.backward()
需要說明的是,所有的參與到b,w的計算的都是需要梯度的參數,例如這里面的yhat,error,loss,都是通過w,b的計算得來的,我們都認為是傳遞了梯度的計算特性
需要特別注意的是,這里的梯度是累計的,因為為了后續的小批量的情況,所以每次更新完畢以后需要手動設置gard_zero_()函數
b.grad.zero_(), w.grad.zero_()
還需要特別注意的是,我們更新參數的時候,是不能直接更新的,需要使用
with torch.no_grad():b -= lr * b.gradw -= lr * w.grad
這在停一下,除了前面的變量的配置不一樣的地方,我們這里已經在改造我們的numpy代碼了
# 原來的numpy的梯度的計算需要手動計算# Step 3 - Computes gradients for both "b" and "w" parametersb_grad = 2 * error.mean()w_grad = 2 * (x_train * error).mean()#但是這里已經可以使用自動計算的方法loss.backward()#可以直接讀取當前的梯度的值b.gradw.grad
動態計算圖
可以使用動態計算圖,直接看到當前的所有的梯度的變量的相互之間的關系,這里大家可以自己看,我就不放出來了
優化器
我們之前都要手動的執行backward,然后獲取b,w的grad,然后手動的進行更新使用了learning rate,最后還需要zero_grad。我們可以通過優化器的方式將變量一開始就加入到優化器中
optimizer = optim.SGD([b,w],lr = lr)# ....執行學習的步驟loss.backward()optimizer.step()#一次性更新所有的參數的變量optimizer.zero_grad()#一次性zero所有的變量的值
損失函數
實際上,我們的損失函數也有torch的封裝,可以直接使用已經配置好的損失函數
loss_fn = nn.MSELoss(reduction = ‘mean’)
損失函數直接得到我們的yhat的結果和y_lable之間的損失的值
#原文中的損失函數的部分error = (yhat - y_train_tensor)loss = (error**2).mean()#取代后loss_fn = nn.MSELoss(reduction='mean')loss = loss_fn(y_hat,y_train_tensor)此時的loss計算出來的結果和之前的是一模一樣的
需要注意的是,如果此時需要回歸的numpy,需要執行detach()操作,表示Loss函數不再參與grad的計算
模型
我們已經有了優化器(用于更新參數),損失函數(用于生成損失值),我們還可以定義自己的module模型(顯然嗎,我們還需要構建很多的我們自己的東西)
我們使用model函數來用現有的模型針對輸入得到我們的輸出函數,model函數對比forward函數,還會 前向和反向的鉤子函數
我們聲明一個繼承與Module的自己的類
class ManualLinearRegression(nn.Module):def __init__(self):super().__init__()# To make "b" and "w" real parameters of the model,# we need to wrap them with nn.Parameterself.b = nn.Parameter(torch.randn(1,requires_grad=True, dtype=torch.float))self.w = nn.Parameter(torch.randn(1, requires_grad=True,dtype=torch.float))def forward(self, x):# Computes the outputs / predictionsreturn self.b + self.w * x
通過parameters的函數,我們可以得到一個module類的目前包含的參數
dummpy = ManualLinearRegression()
list(dummy.parameters)
[Parameter containing:tensor([0.3367], requires_grad=True), Parameter containing:tensor([0.1288], requires_grad=True)]
也可以state_dict來獲取所有的參數的當前值,和parameters的區別在于state_dict通常用于加載和保存模型,而前面的通常用于展示優化器的包含的變量
注意,數據和模型需要在同一個設備
dummy = ManualLinearRegression().to(device)
階段代碼
經過我們的使用自己的類以后的代碼可以優化如下
# Greek letter
lr = 0.1# Step 0 - Initializes parameters "b" and "w" randomly
torch.manual_seed(42)
# Now we can create a model and send it at once to the device
model = ManualLinearRegression().to(device)# Defines a SGD optimizer to update the parameters
# (now retrieved directly from the model)
optimizer = optim.SGD(model.parameters(), lr=lr)# Defines a MSE loss function
loss_fn = nn.MSELoss(reduction='mean')# Defines number of epochs
n_epochs = 1000for epoch in range(n_epochs):model.train() # What is this?!?# Step 1 - Computes model's predicted output - forward pass# No more manual prediction,直接使yhat = model(x_train_tensor)# 一定注意這里使用的是model而不是forward# Step 2 - Computes the lossloss = loss_fn(yhat, y_train_tensor)# Step 3 - Computes gradients for both "b" and "w" parametersloss.backward()# Step 4 - Updates parameters using gradients and# the learning rateoptimizer.step()optimizer.zero_grad()# We can also inspect its parameters using its state_dict
print(model.state_dict())
model.train()
這個是配置了訓練模式,訓練模式可以有很多內容,例如我們常見的dropout的優化模式來減少過擬合的問題
嵌套模型
我們可以使用了已經有的模型來作為嵌套的模型
首先我們使用nn自帶的Linear來取代我們手寫的線性的Module,如下是一個具有一個權重w,和一個bias的線性模型,我們完全可以用這個來取代我們之前的手寫的類
linear = nn.Linear(1,1)
當然我們可以嵌套這個到我們自己的類,這個和之前的基本上是完全等價的
class MyLinearRegression(nn.Module):def __init__(self):super().__init__()# Instead of our custom parameters, we use a Linear model# with single input and single outputself.linear = nn.Linear(1, 1)def forward(self, x):# Now it only takes a callself.linear(x)
序列模型
一個好的深度學習的模型,顯然不只有一層,通常都會有很多隱藏層,將所有的封裝子在一起,我們可以認為是一個序列模型
# Building the model from the figure above
model = nn.Sequential(nn.Linear(3, 5), nn.Linear(5, 1)).to(device)model.state_dict()
注意這里創建了一個序列類,序列類里面有兩層,第一層是一個35的輸出,第二層是一個51的模型,或者我們可以通過添加層的方式來增加帶名字的層
# Building the model from the figure above
model = nn.Sequential()
model.add_module('layer1', nn.Linear(3, 5))
model.add_module('layer2', nn.Linear(5, 1))
model.to(device)
這里其實已經涉及到了深度學習的部分,pytorch的層只是很多例如
卷積層、池化層、填充層、非線性激活層、歸一化層、循環層、transformer層、線性層、丟棄層、稀疏層、視覺層、數據平移(多GPU),展平層