| import jittor as jt |
| |
| from jittor import Module |
| |
| from jittor import nn |
| import numpy as np |
| import matplotlib |
| matplotlib.use('TkAgg') |
| import matplotlib.pyplot as plt |
|
|
| |
|
|
| |
| class Model(Module): |
| def __init__(self): |
| self.layer1 = nn.Linear(1, 10) |
| self.relu = nn.Relu() |
| self.layer2 = nn.Linear(10, 1) |
| def execute (self,x) : |
| x = self.layer1(x) |
| x = self.relu(x) |
| x = self.layer2(x) |
| return x |
|
|
| def get_data(n): |
| for i in range(n): |
| |
| |
| |
| |
| x = np.random.rand(batch_size, 1) |
| y = x*x |
| |
| yield jt.float32(x), jt.float32(y) |
|
|
|
|
|
|
| |
| np.random.seed(0) |
| jt.set_seed(3) |
| n = 1000 |
| batch_size = 50 |
|
|
| |
| model = Model() |
| |
| learning_rate = 0.1 |
| |
| optim = nn.SGD(model.parameters(), learning_rate) |
| min_loss = 1.0 |
|
|
| |
| plt.ion() |
|
|
| |
| |
| |
| for i,(x,y) in enumerate(get_data(n)): |
| pred_y = model(x) |
| loss = ((pred_y - y)**2) |
| loss_mean = loss.mean() |
| optim.step (loss_mean) |
| |
| |
| if(loss_mean.data[0]<min_loss): |
| min_loss=loss_mean.data[0] |
| |
| plt.clf() |
| plt.suptitle(str(i)+"time loss:"+str(loss_mean.data),fontsize=10) |
| |
| a_graph = plt.subplot(2,1,1) |
| a_graph.set_title('Raw data(x,y)') |
| a_graph.set_xlabel('x',fontsize=10) |
| a_graph.set_ylabel('y',fontsize=10) |
| plt.plot(x.data,y.data,'r^') |
| |
| b_graph=plt.subplot(2,1,2) |
| b_graph.set_title("Fitted data(x,pred_y)") |
| b_graph.set_xlabel('x',fontsize=10) |
| b_graph.set_ylabel('pred_y',fontsize=10) |
| plt.plot(x.data,pred_y.data,'g-') |
| |
| plt.pause(0.4) |
|
|
| |
| plt.ioff() |
| plt.show() |