zoukankan      html  css  js  c++  java
  • 《动手学深度学习》--3 深度学习基础笔记1:Pytorch实现简单的线性回归

    简单记录一下如何使用PyTorch实现线性回归的训练,代码如下:

     1 # 导入所需的包
     2 import torch
     3 import numpy as np
     4 import torch.utils.data as Data
     5 import torch.nn as nn
     6 from torch.nn import init
     7 import torch.optim as optim
     8 
     9 # 1 生成训练数据。
    10 # features是训练数据特征,labels是标签
    11 num_inputs = 2
    12 num_examples = 1000
    13 true_w = [2, -3.4]
    14 true_b = 4.2
    15 features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
    16 labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
    17 labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float) # 加上噪声项:ϵϵ 服从均值为0、标准差为0.01的正态分布
    18 
    19 # 2 读取数据。
    20 # PyTorch提供了data包来读取数据
    21 batch_size = 10
    22 dataset = Data.TensorDataset(features, labels) # 将训练数据的特征和标签组合
    23 data_iter = Data.DataLoader(dataset, batch_size, shuffle=True) # 随机读取小批量
    24 
    25 # 3 定义模型
    26 class LinearNet(nn.Module):
    27     def __init__(self, n_feature):
    28         super(LinearNet, self).__init__()
    29         self.linear = nn.Linear(n_feature, 1)
    30     # forward 定义前向传播
    31     def forward(self, x):
    32         y = self.linear(x)
    33         return y
    34 net = LinearNet(num_inputs)
    35 
    36 # 4 初始化模型参数
    37 init.normal_(net.linear.weight, mean=0, std=0.01)
    38 init.constant_(net.linear.bias, val=0) 
    39 
    40 # 5 定义损失函数
    41 loss = nn.MSELoss()
    42 
    43 # 6 定义优化算法
    44 optimizer = optim.SGD(net.parameters(), lr=0.03)
    45 
    46 # 7 训练模型
    47 num_epochs = 3
    48 for epoch in range(1, num_epochs + 1):
    49     for X, y in data_iter:
    50         output = net(X)
    51         l = loss(output, y.view(-1, 1))
    52         optimizer.zero_grad() # 梯度清零,等价于net.zero_grad()
    53         l.backward()
    54         optimizer.step() #调用optim实例的step函数来迭代模型参数
    55     print('epoch %d, loss: %f' % (epoch, l.item()))
    1 epoch 1, loss: 0.000092
    2 epoch 2, loss: 0.000086
    3 epoch 3, loss: 0.000083

    torch.utils.data模块提供了有关数据处理的工具;

    torch.nn模块定义了大量神经网络的层;

    torch.nn.init模块定义了各种初始化方法;

    torch.optim模块提供了很多常用的优化算法。

  • 相关阅读:
    四种wordpress常用的循环结构
    自动创建网页文章目录结构
    shell
    SSH
    架构
    Https
    if-else、switch、while、for
    do-while
    const
    Tail Call
  • 原文地址:https://www.cnblogs.com/vvzhang/p/14347367.html
Copyright © 2011-2022 走看看