简单的线性回归(纯代码加注释)

简单的线性回归

大学实验课记录

小白学习自用,有错误敬请指出。

from IPython import display
from matplotlib import pyplot as plt
from mxnet import autograd, nd
import random
#导入需要的包

num_inputs = 3
num_examples = 1500
true_w = [4, -2.4,7.1]
true_b = 4.5
features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))     #按正态分布随机生成特征数
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_w[2] * features[:,2] +true_b              #线性模型
labels += nd.random.normal(scale=0.01, shape=labels.shape)                          #增加扰动

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 = nd.array(indices[i: min(i + batch_size, num_examples)])
        yield features.take(j), labels.take(j)  # take 函数根据索引返回对应元素。
#获取小批量样本

batch_size = 30

w = nd.random.normal(scale=0.01, shape=(num_inputs, 1))
b = nd.zeros(shape=(1,))
#创建初始的w和b
w.attach_grad()
b.attach_grad()
#定义他们的导数

def linreg(X, w, b):  
    return nd.dot(X, w) + b           #线性回归表达式

def squared_loss(y_hat, y): 
    return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2      #定义损失函数

def sgd(params, lr, batch_size):  
    for param in params:
        param[:] = param - lr * param.grad / batch_size
#定义优化算法(小批量梯度下降法)

lr = 0.03
num_epochs = 4
net = linreg
loss = squared_loss

for epoch in range(num_epochs):  # 训练模型一共需要 num_epochs 个迭代周期。
    # 在一个迭代周期中,使用训练数据集中所有样本一次(假设样本数能够被批量大小整除)。
    # X 和 y 分别是小批量样本的特征和标签。
    for X, y in data_iter(batch_size, features, labels):
        with autograd.record():
            l = loss(net(X, w, b), y)  # l 是有关小批量 X 和 y 的损失。
        l.backward()  # 小批量的损失对模型参数求梯度。
        sgd([w, b], lr, batch_size)  # 使用小批量随机梯度下降迭代模型参数。
    train_l = loss(net(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().asnumpy()))
    
print(true_w, w)
print(true_b, b)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值