3.2 线性回归的从零开始代码实现
一、代码实现
# %matplotlib inline 语句在PyCharm中会报错,将其删除在代码后使用plt.show()来显示图表
import random
import torch
from d2l import torch as d2l
from matplotlib import pyplot as plt # 用plt.show()方法来显示图表
# ***3.2.1 生成数据集
# 实现方程 y = Xw + b + 噪声
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)
return X, y.reshape((-1, 1)) # 指定为-1的行或列会随机分配一个数据
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w