#pt#课堂代码记录_1

 1 from mpl_toolkits import mplot3d
 2 import numpy as np
 3 import matplotlib.pyplot as plt
 4 from mpl_toolkits.mplot3d import Axes3D
 5 
 6 x_data = [1,2,3,4,5]
 7 y_data = [2,4,6,8,10]
 8 w=1
 9 def forward(x):
10     return x * w
11 def cost(xs,ys):
12     cost = 0
13     for x,y in zip(x_data,y_data):
14         y_pred = forward(x)
15         cost+= (y_pred-y)**2
16         return cost/len(xs)  #除以样本数量 求均值
17 list_epoch = []
18 list_cost = []
19 def gradient(xs,ys):
20     grad = 0
21     for x,y in zip(x_data,y_data):
22         grad += 2*(x*w-y)*x
23         return grad/len(xs)
24 
25 print('predict(after trainning)',4,forward(4))
26 for epoch in range(100):
27     cost_val = cost(x_data,y_data)
28     grad_val = gradient(x_data,y_data)
29     w-=0.01*grad_val
30     list_cost.append(cost_val)
31     list_epoch.append(epoch)
32 
33     print('epoch',epoch,'w=',w,'loss=',cost_val)
34 
35 print('predict(after trainning)',4,forward(4))
36 
37 plt.plot(list_epoch,list_cost,linewidth=5)
38 plt.show()

 

posted @ 2021-09-28 20:07  tanyayangyang  阅读(55)  评论(0)    收藏  举报