源代码:
# %% 生成训练样本
def synthetic_data(w, b, num_examples):
""" 生成 y = Xw + b + 噪声"""
X = torch.normal(0, 1, (num_examples, len(w))) # 均值为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,-1为自动调整行数
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print('features', features[0], '\nlabels', labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
d2l.plt.show() # 添加这一行来显示图像
输出
features tensor([-1.8246, 1.7506])
labels tensor([-5.3920])
<Figure size 350x250 with 1 Axes>
可见并没有如期生成图像
解决办法
可能是由于d2l.plt的绘图问题,将源代码的绘图部分修改为
plt.figure()
plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
plt.show() # 添加这一行来显示图像
完美解决