线性回归的手动实现

线性回归的手动实现

y = x w t + b y=xw^t+b y=xwt+b

导入包
import torch 
from IPython import display 
from matplotlib import pyplot as plt 
import numpy as np 
import random
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)
# 𝜀服从均值0、标准差为0.01

数据展示:

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(indices)  # 样本的读取顺序是随机的 
    for i in range(0, num_examples, batch_size): 
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) #最后一次可能不足一个batch 
        yield  features.index_select(0, j), labels.index_select(0, j)

参数初始化:

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 # 注意这里更改param时用的param.data

模型训练

lr = 0.03 
num_epochs = 3 # 迭代次数
batch_size = 10 
net = linreg # 线性回归网路
loss = squared_loss

for epoch in range(num_epochs):       # 训练模型一共需要num_epochs个迭代周期 
# 在每一个迭代周期中,会使用训练数据集中所有样本一次 
    for X, y in data_iter(batch_size, features, labels):       # data_iter返回两个值:特征和标签 
        l = loss(net(X, w, b), y).sum()     # l是有关小批量X和y的损失 
        l.backward()     # 小批量的损失对模型参数求梯度 
        sgd([w, b], lr, batch_size)     # 使用小批量随机梯度下降迭代模型参数 
        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(true_w, '\n', w) 
print(true_b, '\n', b)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值