动手学深度学习笔记|3.2线性回归的从零开始实现(附课后习题答案)
来源: myluster的github笔记,求个star说是
线性回归的从零开始实现
import random
import torch
import matplotlib.pyplot as plt
import numpy as np
生成数据集
def synthetic_data(w,b,num_examples):#@save
#有@save标记的函数是以后课程也需要的函数
#num_examples是需要生成的数据量
X=torch.normal(0,1,(num_examples,len(w)))#随机生成X值
y=torch.matmul(X,w)+b#点乘
y+=torch.normal(0,0.01,y.shape)#加入噪声
return X,y.reshape(-1,1)#y原本为1D向量,需要配合X转换为2D向量
- X 的形状是 (num_examples, len(w))。
- w 的形状是 (len(w),)。
- torch.matmul(X, w) 的结果是一个 1D 张量(向量),形状为 (num_examples,)。
- 加上标量 b 后,y 的形状仍然是 (num_examples,)
true_w=torch.tensor([2,-3.4])
true_b=4.2
features,labels=synthetic_data(true_w,true_b,1000)
print('features:', features[0],'\nlabel:', labels[0])