线性回归 - 代码 (不使用框架实现)

本文通过Python的PyTorch库,不使用框架直接实现了一个线性回归模型。首先创建了合成数据集,然后定义了模型参数、线性回归模型、均方误差损失函数以及小批量随机梯度下降优化器。在训练过程中,以小批量的方式迭代数据并更新模型参数。最后,比较了训练得到的参数与真实参数的差距以评估模型性能。
摘要由CSDN通过智能技术生成

这部分是以实现线性回归为主, 当中是代码, 将会不使用框架实现

详见代码, 里面已尽量给予解释

import torch
import random

# 自创数据集
def synthetic_data(w, b, num_examples):
  x = torch.normal(0, 1, (num_examples, len(w)))
  y = torch.matmul(x, w) + b
  y += torch.normal(0, 0.01, y.shape) # add noise
  return x, y.reshape((-1, 1))

# default: w=[2, -3.4].T, b=4.2
true_w = torch.tensor([2, -3.4])
true_b = 4.2

features, labels = synthetic_data(true_w, true_b, 1000)

# 每次读取小批量
def data_iter(batch_size, features, labels):
  num_examples = len(features)
  indices = list(range(num_examples))
  random.shuffle(indices) # 样本是random取的, 没有特定顺序

  for i in range(0, num_examples, batch_size):
    batch_indices = torch.tensor(indices[i:min(i+batch_size, num_examples)])
    yield features[batch_indices], labels[batch_indices]

# 定义model params
# 对bias进行更新, 所以requires_grad=True
w = to
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值