pytorch 学习笔记 part 1线性回归

一、线性回归

1.从零开始实现线性回归模型

导入模块:

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

print(torch.__version__)

使用如下的线性模型来预测房价:
在这里插入图片描述

# 设置输入特征的数量num_inputs,这里使用了两个特征所以设置为2
num_inputs = 2
# 在这里我们自己生成数据,设置样本数量为1000
num_examples = 1000

# 设置真实的权重和偏差,这两个参数也是要训练学习的两个参数,在这里设置是为了通过特征来生成对应的标签
true_w = [2, -3.4]
true_b = 4.2

#使用torch的随机函数来生成特征,生成1000个样本,每个样本有两个数,所以生成的是一个1000×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)

下面设置展示的图像类型,这里设置为向量图:

def use_svg_display():
    display.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5,2.5)):
    use_svg_display()
    plt.rcParams['figure.figsize']=figsize

set_figsize()
plt.scatter(features[:, 1].numpy(), labels.numpy(), 1);

接下来读取数据集:

def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    #使用random.shuffle对数据集进行打乱
    random.shuffle(indices)  # random read 10 samples
    for i in range(0, num_examples, batch_size):
    	#从数据集中取出i到i+batch_size作为样本,若i + batch_size>1000,则取出样本数量1000
        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

初始化模型参数:

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)

定义用来训练参数的训练模型:

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

定义损失函数
我们使用的是均方误差损失函数:
在这里插入图片描述

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

定义优化函数
在这里优化函数使用的是小批量随机梯度下降:
在这里插入图片描述

def sgd(params, lr, batch_size): 
    for param in params:
        param.data -= lr * param.grad / batch_size # 使用.data是不希望对参数优化的动作被附加

当数据集、模型、损失函数和优化函数定义完了之后就可来准备进行模型的训练了

# 初始化超参数
lr = 0.03 # 学习率
num_epochs = 5 # 训练周期

net = linreg # 单层训练网络
loss = squared_loss # 均方误差损失函数

# training
for epoch in range(num_epochs):  # 第一个for循环是训练周期的循环
    # 每一个训练周期会把训练集中的数据全部取出来使用一次
    
    # X is the feature and y is the label of a batch sample
    for X, y in data_iter(batch_size, features, labels): # 第二个for循环是在数据集中取数据
        l = loss(net(X, w, b), y).sum()  
        # 反向传播求梯度
        l.backward()  
        # 传入需要优化的参数以及学习率和批量大小进行优化
        sgd([w, b], lr, batch_size)  
        # 使梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    当一个训练周期训练完成之后,需要对现在的模型计算损失,在这里把特征、权重和偏差传入到网络中进行预测,再把预测出的y的估计值和标签传入损失函数计算损失,最后打印出周期和周期对应的损失
    train_l = loss(net(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
w, true_w, b, true_b

输出结果:
在这里插入图片描述

2.利用pytorch简洁实现

import torch
from torch import nn
import numpy as np
torch.manual_seed(1)

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

生成数据集

在这里生成数据集跟从零开始的实现中是完全一样的。

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)

读取数据集

import torch.utils.data as Data

batch_size = 10

# 将特征和标签组合起来形成数据集
dataset = Data.TensorDataset(features, labels)

# 使用DataLoader从数据集中取数据,
data_iter = Data.DataLoader(
    dataset=dataset,            # torch TensorDataset format
    batch_size=batch_size,      # 每次取的批量大小batch size
    shuffle=True,               # 是否是随机取出
    num_workers=2,              # 取数据时的线程
)

for X, y in data_iter:
    print(X, '\n', y)
    break

定义模型

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)
# 生成多层网络的方法
# 法一:调用神经网络中的Sequential函数,把不同的层作为参数输入
net = nn.Sequential(
    nn.Linear(num_inputs, 1)
    # other layers can be added here
    )

# 法二:通过add_module函数来添加不同的网络层
net = nn.Sequential()
net.add_module('linear', nn.Linear(num_inputs, 1))
# net.add_module ......

# 法三:把神经网络层放入一个有序的字典里来传入到Sequential函数中
from collections import OrderedDict
net = nn.Sequential(OrderedDict([
          ('linear', nn.Linear(num_inputs, 1))
          # ......
        ]))

print(net)
print(net[0])

初始化模型参数

from torch.nn import init

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)

定义损失函数

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

定义优化函数

import torch.optim as optim

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)`

训练

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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值