isLandLZ commited on
Commit
7a82d34
·
1 Parent(s): 6c54fc8

Upload LinearRegression_Model.py

Browse files
Files changed (1) hide show
  1. LinearRegression_Model.py +87 -0
LinearRegression_Model.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import jittor as jt
2
+ #骨干网络模块
3
+ from jittor import Module
4
+ #神经网络模块
5
+ from jittor import nn
6
+ import numpy as np
7
+ import matplotlib
8
+ matplotlib.use('TkAgg')
9
+ import matplotlib.pyplot as plt
10
+
11
+ #线性回归实例
12
+
13
+ #该模型是一个两层神经网络。 隐藏层的大小为10,激活函数为relu
14
+ class Model(Module):
15
+ def __init__(self):
16
+ self.layer1 = nn.Linear(1, 10)
17
+ self.relu = nn.Relu()
18
+ self.layer2 = nn.Linear(10, 1)
19
+ def execute (self,x) :
20
+ x = self.layer1(x)
21
+ x = self.relu(x)
22
+ x = self.layer2(x)
23
+ return x
24
+
25
+ def get_data(n): # generate random data for training test.
26
+ for i in range(n):#n=1000
27
+ #产生一个numpy.ndarray数据类型的列表
28
+ #其中包含batch_size(50)个numpy.ndarray数据类型的列表x
29
+ #每个小列表里只有一个(0,1)的数,数据类型是'numpy.float64,x[index]
30
+ #y跟x一样
31
+ x = np.random.rand(batch_size, 1)
32
+ y = x*x
33
+ #返回一个generator实例
34
+ yield jt.float32(x), jt.float32(y)
35
+
36
+
37
+
38
+ #随机数种子对后面的结果一直有影响,后面的随机数组都是按一定的顺序生成的
39
+ np.random.seed(0)
40
+ jt.set_seed(3)
41
+ n = 1000
42
+ batch_size = 50
43
+
44
+ #新建模型
45
+ model = Model()
46
+ #设置学习效率
47
+ learning_rate = 0.1
48
+ #保持当前参数状态并基于计算得到的梯度进行参数更新
49
+ optim = nn.SGD(model.parameters(), learning_rate)
50
+ min_loss = 1.0
51
+
52
+ #开启一个画图的窗口进入交互模式,实时更新数据
53
+ plt.ion()
54
+
55
+ #优化器使用简单的梯度下降,损失函数为L2距离
56
+ #enumerate:将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
57
+ #列表中的每个元素都是元组(x,y)
58
+ for i,(x,y) in enumerate(get_data(n)):
59
+ pred_y = model(x)
60
+ loss = ((pred_y - y)**2)
61
+ loss_mean = loss.mean()
62
+ optim.step (loss_mean)
63
+ #print(f"step {i}, loss = {loss_mean.data.sum()}")
64
+ #根据每次的loss来选择是否绘图,保证最后一张图的loss最小
65
+ if(loss_mean.data[0]<min_loss):
66
+ min_loss=loss_mean.data[0]
67
+ #清除刷新前的图
68
+ plt.clf()
69
+ plt.suptitle(str(i)+"time loss:"+str(loss_mean.data),fontsize=10)
70
+ #第一张图
71
+ a_graph = plt.subplot(2,1,1)
72
+ a_graph.set_title('Raw data(x,y)')
73
+ a_graph.set_xlabel('x',fontsize=10)
74
+ a_graph.set_ylabel('y',fontsize=10)
75
+ plt.plot(x.data,y.data,'r^')
76
+ #第二张图
77
+ b_graph=plt.subplot(2,1,2)
78
+ b_graph.set_title("Fitted data(x,pred_y)")
79
+ b_graph.set_xlabel('x',fontsize=10)
80
+ b_graph.set_ylabel('pred_y',fontsize=10)
81
+ plt.plot(x.data,pred_y.data,'g-')
82
+ #弹窗停留0.4秒
83
+ plt.pause(0.4)
84
+
85
+ #关闭交互模式
86
+ plt.ioff()
87
+ plt.show()