李宏毅机器学习-pockmon demo源码实现如下,相关代码的个人理解均在注释中给出。
import numpy as np import matplotlib.pyplot as plt x_data = [338., 333., 328., 207., 226., 25., 179., 60., 208., 606.] y_data = [640., 633., 619., 393., 428., 27., 193., 66., 226., 1591.] # y_data = b + w * x_data x = np.arange(-200, -100, 1) # bias y = np.arange(-5, 5, 0.1) # weight z = np.zeros((len(x), len(y))) # zeros函数表示输出的数组为301行101列 X, Y = np.meshgrid(x, y) # 扩展矩阵,X扩展为11*301的横向量矩阵,Y扩展为101*301的列向量矩阵 for i in range(len(x)): for j in range(len(y)): b = x[i] w = y[j] z[j][i] = 0 for n in range(len(x_data)): z[j][i] = z[j][i] + (y_data[n] - b - w*x_data[n])**2 # z[j][i]为b=x[i]及w=y[j]时,对应的Loss Function的大小 z[j][i] = z[j][i]/len(x_data) # 单个数据的训练集偏差值 # ydata = b + w * xdata b = -120 # initial b w = -4 # initial w lr = 1 # learning rate iteration = 100000 # 迭代运行次数 # store initial values for plotting b_history = [b] w_history = [w] lr_b = 0 # 给b和w分别赋予不同的learning rate值 lr_w = 0 # iterations for i in range(iteration): # 在100000次迭代下,看最后结果 b_grad = 0.0 # 对b_grad重新赋值为0 w_grad = 0.0 # 对w_grad重新赋值为0 for n in range(len(x_data)): # 此处应该注意的是,求导的是L函数,因此对应的变量是w、b,是看w、b在各自的轴上的移动 # 所以,x_data,y_data上的都只是数据,一定要注意区分!!! b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0 w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n] # 因为这两个值是计算历次b_grad、w_grad的平方和值之和,方便下面Adagrad方法应用 lr_b = lr_b + b_grad ** 2 lr_w = lr_w + w_grad ** 2 # update parameters b = b - lr/np.sqrt(lr_b) * b_grad # 此处用到Adagrad(随着迭代次数增加,lr会变得越来越小)方法 w = w - lr/np.sqrt(lr_w) * w_grad # 这样可以更加有效的找到minima # store parameters for plotting b_history.append(b) w_history.append(w) # plot the figure plt.contourf(x, y, z, 50, alpha=0.5, cmap=plt.get_cmap('jet')) plt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange') plt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black') plt.xlim(-200, -100) plt.ylim(-5, 5) plt.xlabel(r'$b$', fontsize=16) plt.ylabel(r'$w$', fontsize=16) plt.show()