1 %matplotlib inline
2 from IPython import display
3 from matplotlib import pyplot as plt
4 from mxnet import autograd, nd
5 import random
6
7 num_inputs = 2
8 num_examples = 1000
9 true_w = [2, -3.4]
10 true_b = 4.2
11 features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))
12 labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
13
14 def use_svg_display():
15 # 用矢量图显示
16 display.set_matplotlib_formats('svg')
17
18 def set_figsize(figsize=(3.5, 2.5)):
19 use_svg_display()
20 # 设置图的尺寸
21 plt.rcParams['figure.figsize'] = figsize
22
23 set_figsize()
24 plt.scatter(features[:, 1].asnumpy(), labels.asnumpy(), 1); # 加分号只显示图
25
26
27 # 本函数已保存在d2lzh包中方便以后使用
28 def data_iter(batch_size, features, labels): #数据迭代器,用来存储遍历所有的子集样本
29 num_examples = len(features)
30 indices = list(range(num_examples))
31 random.shuffle(indices) # 样本的读取顺序是随机的
32 for i in range(0, num_examples, batch_size):
33 j = nd.array(indices[i: min(i + batch_size, num_examples)])
34 yield features.take(j), labels.take(j) # take函数根据索引返回对应元素
35
36 batch_size=10
37 for x,y in data_iter(batch_size,features,labels):
38 print(x,y)
39 break
40
41 w=nd.random.normal(scale=0.01,shape=(num_inputs,1)) #c初始化模型参数
42 b=nd.zeros(shape=(1,))
43
44 w.attach_grad()
45 b.attach_grad() #申请求导内存
46
47 def linreg(X,w,b): #定义模型y^
48 return nd.dot(X,w)+b
49
50 def squared_loss(y_hat,y): #定义损失函数的类型,此处为平方损失,把上面的y^放到这里,即
51 #y_hat
52 return (y_hat - y.reshape(y_hat.shape))**2/2
53
54
55 def sgd(params,lr,batch_size): #定义参数的更新方法,lr:学习率,params指参数有多个。
56 for param in params:
57 param[:]=param-lr*param.grad/batch_size
58
59 ##前面定义好了所有的东西,数据读取,参数处世权值,模型,损失函数,参数更新;最后揉到一起完成训练过程。
60 lr=0.03
61 num_epochs = 3 #epoch,即训练一次,完成一次反向传播的过程。
62 net = linreg
63 loss = squared_loss
64 for epoch in range(num_epochs):
65 for X, y in data_iter(batch_size, features, labels):
66 with autograd.record():
67 l = loss(net(X, w, b), y) # l是有关小批量X和y的损失 每一个样本求一个loss,然后给参数更新一下,最终的参数是将所有的梯度加在一起了。
68 l.backward() # 小批量的损失对模型参数求梯度
69 sgd([w, b], lr, batch_size) # 使用小批量随机梯度下降迭代模型参数
70 train_l = loss(net(features, w, b), labels) #最后一次迭代的损失,也即一轮结束后的损失。
71 print('epoch %d , loss %f' % (epoch + 1, train_l.mean().asnumpy()))