本文内容,参考自:https://peterroelants.github.io/posts/neural-network-implementation-part01/
import numpy as np from matplotlib import pyplot as plt #定义--------------------------------------------------------begin #训练数据 x x = np.linspace(0,2,20) #以0.1为间隔,在0-2之间生成20个数据。 data_size = len(x) #Guassian noise np.random.seed(5) noise = np.random.randn(data_size) * 0.2 #高斯分布~ N(0,0.04) #target y y = 2 * x + noise #在真实情况下,我们并不知道 y与x的关系。我们要计算求解的正是这个关 系。 #weights w np.random.seed(6) w = np.random.randn() #梯度下降求解权重参数w,随机初始化 #learning rate u u = 0.1 #network def network(x,w): return x*w def loss(pred,y): #预测值和target值,在此使用MSE return np.sum(np.square(y-pred)) / len(pred) #定义--------------------------------------------------------end epochs = 20 delta_w_list = [] for i in range(epochs): pred = network(x,w) plt.plot(x,pred,marker='x',linestyle='--', label=str(i) + 'w:%.3f' % w) delta_w = np.sum(2 * x * u * ( pred - y)) / data_size delta_w_list.append(delta_w) w = w - delta_w print (w) plt.plot(x, delta_w_list, marker='+',linestyle='-',label='delta_w') plt.plot(x,y,marker='o',linestyle=':',label='target') plt.legend(loc='upper left') plt.show()
显示结果图: