#导入包
%matplotlib inline
import random
import torch
from d2l import torch as d2l
#生成数据集
def synthetic_data(w, b, num_examples): #@save
"""生成y=Xw+b+噪声"""
X = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape) #加入噪声
return X, y.reshape((-1, 1))
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.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)
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]
#初始化模型参数
w = torch.normal(0, 0.01, size=(2,1), requires_grad&
从零开始实现线性回归模型(SDG,MSE),未使用深度学习框架
最新推荐文章于 2024-07-02 23:02:27 发布
本文介绍了如何从零开始构建线性回归模型,不依赖深度学习框架,通过梯度下降算法优化权重,并用均方误差作为损失函数进行评估。详细阐述了线性回归的基础原理及实现步骤。
摘要由CSDN通过智能技术生成