动手学深度学习之线性回归

蹲街弑〆低调 提交于 2020-02-15 08:48:56

1. 线性回归基本要素

1.1 模型

所谓模型,即两种或两种以上变量间相互依赖的定量关系。例如:房价受其面积、地段与房龄等因素的制约

1.2 数据集

为了对某现象进行预测,需要已知该现象在一段时间内的确切数据。以期在该数据基础上面寻找模型参数来使模型的预测值与真实值的误差最小。在机器学习术语里,该数据集被称为训练数据集(training data set)训练集(training set),其中个体被称为样本(sample),其真实值称为标签(label),用来预测标签的因素称为特征(feature)。特征用于表征样本的特点。

1.3 损失函数

在模型训练中,需要衡量预测值与真实值之间的误差。通常会选取一个非负数作为误差,其数值越小表示误差越小。一个常用的选择是平方函数

1.4 优化函数

当模型和损失函数形式较为简单时,误差最小化问题的解可以直接用公式表达出来,这类解称为解析解(analytical solution)。本节使用的线性回归和平方误差刚好属于这个范畴。然而,大多数深度学习模型并没有解析解,只能通过优化算法有限次迭代模型参数来尽可能降低损失函数的值,这类解称为数值解(numerical solution)。在求数值解的优化算法中,小批量随机梯度下降(mini-batch stochastic gradient descent)在深度学习中被广泛使用。它的算法很简单:先取一组模型参数的初始值(如随机选取),对其参数进行多次迭代,使每次迭代都可能降低损失函数的值。在每次迭代中,先随机均匀采样一个由固定数目训练数据样本所组成的小批量(mini-batch),然后求小批量中数据样本的平均损失有关模型参数的导数(梯度),最后用此结果与预先设定的一个正数的乘积作为模型参数在本次迭代的减小量。

总结而言,优化函数的有以下两个步骤:

  1. 初始化模型参数,一般来说使用随机初始化;
  2. 多次迭代数据,通过在负梯度方向移动参数来更新每个参数。

2. 从零开始实现线性回归

此时假设房价仅受面积与房龄两个因素约束

2.1 import模块

# import packages and modules
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random

print(torch.__version__)

2.2 生成数据集

通过房价与面积/房龄间的定量关系price=wareaarea+wageage+bprice=w_{area}\cdot area+w_{age}\cdot age+b生成一个1000个样本的数据集

# set input feature number 
num_inputs = 2
# set example number
num_examples = 1000

# set true weight and bias in order to generate corresponded label
true_w = [2, -3.4]
true_b = 4.2

features = torch.randn(num_examples, num_inputs,
                      dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()),
                       dtype=torch.float32)

2.3 读取数据集

def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)  # random read 10 samples
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
        yield  features.index_select(0, j), labels.index_select(0, j)

batch_size = 10
for X, y in data_iter(batch_size, features, labels):
    print(X, '\n', y)
    break
tensor([[-0.2891, -1.1804],
        [ 1.0788,  2.0177],
        [ 0.6912, -0.7635],
        [ 0.2029, -2.1475],
        [ 0.1921, -0.1297],
        [-1.1457, -0.2034],
        [ 0.4795,  0.0445],
        [-1.6393, -0.9503],
        [-1.1661,  0.8298],
        [ 1.0865,  1.2341]])
 tensor([ 7.6385, -0.4946,  8.1807, 11.9086,  5.0154,  2.6114,  5.0170,  4.1535,
        -0.9633,  2.1629])

2.4 初始化模型参数

w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)

w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)

2.5 定义模型

定义用来训练参数的训练模型,即生成数据所用的定量关系

def linreg(X, w, b):
    return torch.mm(X, w) + b

2.6 定义损失函数

使用均方差损失函数

def squared_loss(y_hat, y): 
    return (y_hat - y.view(y_hat.size())) ** 2 / 2

2.7 定义优化函数

使用随机梯度下降函数

def sgd(params, lr, batch_size): 
    for param in params:
        param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track

2.8 训练

设置超参数学习率/迭代次数,开始训练

# super parameters init
lr = 0.03
num_epochs = 5

net = linreg
loss = squared_loss

# training
for epoch in range(num_epochs):  # training repeats num_epochs times
    # in each epoch, all the samples in dataset will be used once
    
    # X is the feature and y is the label of a batch sample
    for X, y in data_iter(batch_size, features, labels):
        l = loss(net(X, w, b), y).sum()  
        # calculate the gradient of batch sample loss 
        l.backward()  
        # using small batch random gradient descent to iter model parameters
        sgd([w, b], lr, batch_size)  
        # reset parameter gradient
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(w, true_w, b, true_b)
epoch 1, loss 0.043447
epoch 2, loss 0.000172
epoch 3, loss 0.000050
epoch 4, loss 0.000050
epoch 5, loss 0.000050
tensor([[ 2.0003],
        [-3.3997]], requires_grad=True) [2, -3.4] tensor([4.2003], requires_grad=True) 4.2

3. pytorch简单实现

3.1 import模块

import torch
from torch import nn
import numpy as np
import torch.utils.data as Data
from torch.nn import init
import torch.optim as optim

torch.manual_seed(1)#随机初始化种子,保证每次初始化的值相同

print(torch.__version__)
torch.set_default_tensor_type('torch.FloatTensor')

3.2 生成数据集

num_inputs = 2
num_examples = 1000

true_w = [2, -3.4]
true_b = 4.2

features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)

3.3 读取数据集

batch_size = 10

# combine featues and labels of dataset
dataset = Data.TensorDataset(features, labels)

# put dataset into DataLoader
data_iter = Data.DataLoader(
    dataset=dataset,            # torch TensorDataset format
    batch_size=batch_size,      # mini batch size
    shuffle=True,               # whether shuffle the data or not
    num_workers=2,              # read data in multithreading
)

for X, y in data_iter:
    print(X, '\n', y)
    break
tensor([[-0.4445,  1.7302],
        [ 0.2253, -0.9533],
        [ 0.3372, -1.1818],
        [ 0.0382, -0.1883],
        [ 1.0867, -0.9743],
        [ 0.4982, -0.6187],
        [-0.7223, -1.0205],
        [ 1.4663,  1.8000],
        [ 1.0313, -0.0074],
        [-0.3015, -0.3170]])
 tensor([-2.5861,  7.8909,  8.8916,  4.9161,  9.6944,  7.3101,  6.2225,  1.0236,
         6.3070,  4.6766])

3.4 定义模型

class LinearNet(nn.Module):
    def __init__(self, n_feature):
        super(LinearNet, self).__init__()      # call father function to init 
        self.linear = nn.Linear(n_feature, 1)  # function prototype: `torch.nn.Linear(in_features, out_features, bias=True)`

    def forward(self, x):
        y = self.linear(x)
        return y
    
net = LinearNet(num_inputs)
print(net)

# ways to init a multilayer network
# method one
net = nn.Sequential(
    nn.Linear(num_inputs, 1)
    # other layers can be added here
    )

# method two
net = nn.Sequential()
net.add_module('linear', nn.Linear(num_inputs, 1))
# net.add_module ......

# method three
from collections import OrderedDict
net = nn.Sequential(OrderedDict([
          ('linear', nn.Linear(num_inputs, 1))
          # ......
        ]))

print(net)
print(net[0])
LinearNet(
  (linear): Linear(in_features=2, out_features=1, bias=True)
)
Sequential(
  (0): Linear(in_features=2, out_features=1, bias=True)
)
Linear(in_features=2, out_features=1, bias=True)

3.5 初始化模型参数

init.normal_(net[0].weight, mean=0.0, std=0.01)
init.constant_(net[0].bias, val=0.0)  # or you can use `net[0].bias.data.fill_(0)` to modify it directly
for param in net.parameters():
    print(param)
Parameter containing:
tensor([[0.0206, 0.0077]], requires_grad=True)
Parameter containing:
tensor([0.], requires_grad=True)

3.6 定义损失函数

loss = nn.MSELoss()    # nn built-in squared loss function
                       # function prototype: `torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')`

3.7 定义优化函数

optimizer = optim.SGD(net.parameters(), lr=0.03)   # built-in random gradient descent function
print(optimizer)  # function prototype: `torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)`
SGD (
Parameter Group 0
    dampening: 0
    lr: 0.03
    momentum: 0
    nesterov: False
    weight_decay: 0
)

3.8 训练

num_epochs = 3
for epoch in range(1, num_epochs + 1):
    for X, y in data_iter:
        output = net(X)
        l = loss(output, y.view(-1, 1))
        optimizer.zero_grad() # reset gradient, equal to net.zero_grad()
        l.backward()
        optimizer.step()
    print('epoch %d, loss: %f' % (epoch, l.item()))

# result comparision
dense = net[0]
print(true_w, dense.weight.data)
print(true_b, dense.bias.data)
epoch 1, loss: 0.000033
epoch 2, loss: 0.000119
epoch 3, loss: 0.000071
[2, -3.4] tensor([[ 2.0005, -3.4003]])
4.2 tensor([4.1995])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!