线性回归的从零开始实现
从零开始实现整个方法,包括数据流水线、模型、损失函数和小批量随机梯度下降优化器
%matplotlib inline
#将matplot的图嵌入代码当中
import random
import torch
from d2l import torch as d2l
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
根据带有噪声的线性模型构造一个人造数据集。我们使用线性模型参数w = [2,-3,4]^T、b = 4.2和噪声项c生成数据集及其标签:
y = Xw + b + c
def synthetic_data(w,b,num_examples):
"""生成 y = Xw + b + 噪声。"""
X = torch.normal(0, 1, (num_examples,len(w)))
#torch.normal()是PyTorch中用于生成服从正态分布的随机数的函数。
#参数为(均值,标准差,形状)
y = torch.matmul(X,w) + b
#torch.matual()可用于张量与矩阵相乘
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 = synthetic_data(true_w,true_b,1000)
#y的形状:【1000,3】*【3,1】 = 【1000,1】
#X:[1000,3] y:[1000,1]
print('features:',features[0],'\nlabel:',labels[0])#打印数据集第一项和标签第一项
features: tensor([ 0.0471, -0.8223])
label: tensor([7.0853])
d2l.set_figsize()
d2l.plt.scatter(features[: