打卡-Task01:线性回归;Softmax与分类模型;多层感知机

本文介绍了线性回归在回归问题中的应用,以及如何使用NDArray和autograd实现线性回归的训练。通过生成的人工数据集,展示了模型训练过程,包括损失函数、优化算法和参数更新。最后,文章提到了学习过程中遇到的挑战,表示对后续内容的理解尚有困难。
摘要由CSDN通过智能技术生成

线性回归输出是一个连续值,因此适用于回归问题。回归问题在实际中很常见,如预测房屋价格、气温、销售额等连续值的问题。与回归问题不同,分类问题中模型的最终输出是一个离散值。我们所说的图像分类、垃圾邮件识别、疾病检测等输出为离散值的问题都属于分类问题的范畴。softmax回归则适用于分类问题。
接下来利用NDArray和autograd来实现一个线性回归的训练。首先,导入本节中实验所需的包或模块,其中的matplotlib包可用于作图,且设置成嵌入显示。

%matplotlib inline
from IPython import display
from matplotlib import pyplot as plt
from mxnet import autograd, nd
import random

我们构造一个简单的人工训练数据集,它可以使我们能够直观比较学到的参数和真实的模型参数的区别。设训练数据集样本数为1000,输入个数(特征数)为2。给定随机生成的批量样本特征 X∈R1000×2 ,我们使用线性回归模型真实权重 w=[2,−3.4]⊤ 和偏差 b=4.2 ,以及一个随机噪声项 ϵ 来生成标签y=Xw+b+ϵ, 其中噪声项 ϵ 服从均值为0、标准差为0.01的正态分布。噪声代表了数据集中无意义的干扰。下面,让我们生成数据集。

# 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)
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)  # 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.2418, 0.0977],
[-1.4690, 1.0187],
[-0.8680, 1.3924],
[-0.2509, 0.0042],
[-0.8196, 2.7727],
[-1.3803, 1.3686],
[ 0.3174, -0.5171],
[-0.7607, 1.2662],
[ 0.6477, -0.4813],
[ 0.4225, -1.1675]])
tensor([ 3.3814, -2.1989, -2.2673, 3.6702, -6.8637, -3.2140, 6.5941, -1.6277,
7.1394, 9.0192])
初始化模型参数

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 # ues .data to operate param without gradient tra

模型训练

# 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()))

输出
epoch 1, loss 0.027050
epoch 2, loss 0.000091
epoch 3, loss 0.000048
epoch 4, loss 0.000048
epoch 5, loss 0.000048

w, true_w, b, true_b

输出
(tensor([[ 1.9996],
[-3.4000]], requires_grad=True),
[2, -3.4],
tensor([4.1999], requires_grad=True),
4.2)
刚接触这些知识点,感觉代码讲解不够详细,跟起来有些吃力,后面的看了但是还没搞懂。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值