机器学习-线性回归的从零手动实现

博客介绍了模型训练的基本要素,包括模型、训练数据、损失函数等。重点阐述了线性回归从零开始的实现步骤,如生成数据集、读取数据、初始化参数、定义模型、损失函数和优化算法,最后完成模型训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先我们先了解一下基本要素

1,模型

2,模型训练

3,训练数据

4,损失函数

5,优化算法(好好学最优化方法)

6,模型预测

 

 

首先线性回归的从零开始

first,生成数据集,函数原型为 y_hat = x1 * w1 + x2 * w2 + b

# 生成数据集
# y_hat = x1 * w1 + x2 * w2 + b
num_input = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = nd.normal(scale = 1, shape = (num_examples, num_input))
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += nd.normal(scale = 0.01, shape = labels.shape)

second,读取数据集

# 读取数据集
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)

third,初始化模型参数

w = nd.normal(scale = 0.01, shape = (num_input, 1))
b = nd.zeros(shape = (1, 1))

next,定义模型

def linreg(X, w, b):
    return nd.dot(X, w) + b

next,定义损失函数 l = (y_hat - y) ^ 2 * 0.5

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

next,定义优化算法 迭代算法,其中params是超参数,lr是学习率,batch_size是批量大小

def sgd(params, lr, batch_size):
    for param in params:
        param[:] = param - lr * param.grad / batch_size

finally, 训练模型

lr = 0.03
num_epochs = 3
for epoch in range(num_epochs): # 一共迭代num_epochs个迭代周期
    for X, y in data_iter(batch_size, features, labels):
        with autograd.record():
            l = squared_loss(linreg(nd.array(X), w, b), y)
        l.backward()
        sgd([w, b], lr, batch_size)
    train_l = squared_loss(linreg(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().asnumpy()))
print(true_w, w)
print(true_b, b)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值