PyTorch 网络搭建训练代码模板

原文排版图片更清楚

原文传送门

神经网路搭建基础

神经网络看起来很复杂,节点很多,层很多,参数更多,但核心部分或组件不多,把这些组件确定后,这个神经网络就确定了。
这些核心组件包括

  1. 层:神经网络的基本结构,将输入张量进行变换
  2. 模型:层构成的网络
  3. 损失函数:参数学习的目标函数,通过最小化损失函数来学习各种参数
  4. 优化器:如何使损失函数最小,这就设计优化器

此处图片参考:图片


多个层连接在一起构成一个模型或网络,
输入数据通过这个模型转换为预测值,
然后损失函数把预测值与真实值进行比较,得到损失值(损失值可以是距离、概率值等),该损失值用于衡量预测值与目标结果的匹配或相似程度,
优化器利用损失值更新权重参数,从而使损失值越来越小。

这是一个循环过程,当损失值达到一个阈值或循环次数达到指定次数,循环结束

实现神经网络

Pytorch的模型通过继承nn.Module类,在模型(子类)定义的内部定义子模块的实例化,通过前向计算调用子模块,最后实现深度学习模型的搭建

此处图片参考:图片

Step1(定义网络结构)


Backward will be inferred automatically if we use the nn.Module class!
**__init__()**define model parameters that will be instantiated when created an object of this class
**farward()**define how and what order the model parameters should be used in the forward pass.

使用super函数来获取当前类的父类nn.Module,然后调用父类的构造函数,从而初始化一些必要的变量和参数。
通过__init__()方法初始化整个模型,一般在__init__()方法中定义好网络的层
定义好每层之后,最后需要通过前向传播的方式把这些层结构串起来,这就是涉及如何定义forward函数的问题。
forward()函数的任务需要把输入层、网络层、输出层连接起来,实现信息的前向传导,该函数的参数一般为输入数据,返回值为输出数据

import torch

class MultilayerPerceptron(torch.nn.Module):
    
    def __init__(self,number_features,num_classes):
        super(MultilayerPerceptron,self).__init__()
        
        ### 1st hidden layer
        self.linear_1 = torch.nn.Linear(num_feat, num_h1)
        ### 2nd hidden layer
        self.linear_2 = torch.nn.Linear(num_h1,num_h2)
       	### Output layer
        self.linear_out = torch.nn.Linear(num_h2,num_classes)
        
    
    def forward(self,x):
        out = self.linear_1(x)
        out = F.relu(out)
        out = self.linaer_2(out)
        out = F.relu(out)
        logits = self.linear_out(out)
        probas = F.log_softmax(logits,dim=1)
        
        return logits,probas

Step2(实例化网络)

**model = MultilayerPerceptron()**– Instantiate model
**optimizer = torch.opti.SGD()** – Define an optimization method
**model = model.to(device)** – Optionally move model to GPU, where device e.g. torch.device(‘cuda:0’)

torch.manual_seed(random_seed)

model = MultilayerPerceptron(num_features = num_features,
                            num_classes = num_classes)
model = model.to(device)
optimizer = torch.optim.SGD(model.parameters(),
                           lr = learning_rate)

Step3(Training)

层、模型、损失函数、优化器都定义或创建好,接下来就是训练模型

1. model.train()

训练模型要注意使得模型处于训练模式,即调用**model.train()**
如果是测试或者验证阶段,需要使模型处于验证阶段,即调用**model.eval()**, 调用model.eval()会把所有的training属性设置为False.

2. for loop

for epoch in range(num_epochs): --> Run for a specified number of epochs

for bach_idx, (features, targets) in enumerate(train_loader): --> Iterate over minibatches in epoch

3. Forward pass

logits, probas = model(features) --> This will run the forward() method


loss = F.cross_entropy(logits,targets) --> Define a loss function to optimize

4. Backward pass

前向传播函数定义好之后,接下来就是梯度的方向传播。PyTorch提供了自动方向传播功能,使用nn工具箱,无须自己编写反向传播函数,直接让损失函数(loss)调用backward()即可
缺省情况下梯度是累加的,需要手工把梯度初始化或者清零,调用**optimizer.zero_grad()**即可
optimizer.zero_grad() --> set the graduent to zero (could be non-zero from a previous forward pass)
训练过程中,正向传播生成网络的输出,计算输出和实际值之间的损失值。
调用**loss.backward()**自动生成梯度,然后使用**optimizer.step()**执行优化器,把梯度传播回每个网络。
loss.backward()–> Compute the gradients, the backward is automatically constructed by “autograd” based on the forward() method and the loss function

5. 设置训练设备

如果希望用GPU训练,需要把模型、训练数据、测试数据发送到GPU上,即调用.to(device)
这里device一般使用 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")初始化

for epoch in range(num_epochs):
    model.train()
    for batch_idx, (features, targets) in enumerate(train_loader):
        
        features = features.view(-1,28,28).to(device)
        targets = target.to(device)
        
        ### Forward and back prop
        logits, probas = model(features)
        cost = F.cross_entropy(probas,targets)
        optimizer.zero_grad()
        
        cost.backward()
        
        ### Update model parameters
        optimizer.step()
    
    model.eval()
    with torch.no_grad():

https://zhuanlan.zhihu.com/p/354850320

训练代码一般写法:

for epoch in range(NUM_EPOCHS):
    model.train()
    for batch_idx, (features, targets) in enumerate(train_loader):
        
        features = features.view(-1, 28*28).to(DEVICE)
        targets = targets.to(DEVICE)
            
        ### FORWARD AND BACK PROP
        logits = model(features)
        
        cost = F.cross_entropy(logits, targets)
        optimizer.zero_grad()
        
        cost.backward()
       
        ### UPDATE MODEL PARAMETERS
        optimizer.step()
        
        ### LOGGING
        minibatch_cost.append(cost.item())
        if not batch_idx % 50:
            print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' 
                   %(epoch+1, NUM_EPOCHS, batch_idx, 
                     len(train_loader), cost.item()))
        
    cost = compute_loss(model, train_loader)
    epoch_cost.append(cost)
    print('Epoch: %03d/%03d Train Cost: %.4f' % (
            epoch+1, NUM_EPOCHS, cost))
    print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))
    
print('Total Training Time: %.2f min' % ((time.time() - start_time)/60))

你可能感兴趣的:(深度学习,pytorch,神经网络,深度学习)