python纯Numpy实现线性回归(随机梯度下降法)

本文详细介绍了如何使用Python的Numpy库实现线性回归,通过随机梯度下降法进行优化。内容包括理论推导、代码实现步骤,如构造数据集、定义模型、损失函数、优化算法等。在实现过程中,还对比了手动求导与自动求导(如PyTorch)在收敛速度上的差异。

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

用Numpy实现线性回归
一、理论推导
损失函数在这里插入图片描述
二、代码实现
引入numpy包和random包

import random
import numpy as np

主要函数如下
1.构造数据集

def synthetic_data(w,b,num_examples):
    #生成y=Xw+b+噪声  (加噪声是为了验证是否可以拟合)  w=[2,-3.4],b=4.2
    X=np.random.normal(0, 1, (num_examples,len(w)))
    y=np.matmul(X,w)+b
    y+=np.random.normal(0,0.01,y.shape)   #取噪声偏置
    return X,y.reshape((-1,1))

2.构造迭代器

def data_iter(bath_size,features,labels):
    num_examples=len(features)
    indices=list(range(num_examples))
    #设置shuffle
    random.shuffle(indices)
    for i in range(0,num_examples,bath_size):
        bath_indices=np.array(indices[i:min(i+bath_size,num_examples)])
        yield features[bath_indices],labels[bath_indices]

3.定义模型

def Linreg(X,w,b):
    return np.matmul(X,w)+b[0]

4.定义损失函数

def squared_loss(y_hat,y,batch_size):
    #均方损失
    return ((y_hat-y)**
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值