使用pytorch实现一个线性回归训练函数

本文介绍了如何使用Python的sklearn库生成线性回归数据集,通过拆分batch训练,并利用梯度下降法优化权重和偏置,展示了数据拟合和损失值变化的过程。

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

使用sklearn.dataset 的make_regression创建用于线性回归的数据集

def create_dataset():
    x, y, coef = make_regression(n_samples=100, noise=10, coef=True, bias=14.5, n_features=1, random_state=0)
    return torch.tensor(x), torch.tensor(y), coef

加载数据集,并拆分batchs训练集

def load_dataset(x, y, batch_size):
    data_len = len(y)
    batch_num = data_len // batch_size
    for idx in range(batch_num):
        start = idx * batch_num
        end = idx * batch_num + batch_num
        train_x = x[start : end]
        train_y = y[start : end]
        yield train_x, train_y

定义初始权重和定义计算函数

w = torch.tensor(0.1, requires_grad=True, dtype=torch.float64)
b = torch.tensor(0, requires_grad=True, dtype=torch.float64)
def linear_regression(x):
    return x * w + b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值