备注下上一节:
https://www.toutiao.com/article/7114563623883735585/
理解就是计算梯度,然后基于梯度做小距离的移动(lr), 这样逐步求解到最小值。
不知道头条为啥把代码屏蔽到只有一行了,这里把代码注释截图出来
求某个函数在某个位置的梯度
基于梯度做一个迭代
初始化函数相关信息:
初始化函数相关信息
备注一下之前做的事情
def numerical_gradient(f, X): if X.ndim == 1: #如果只有一维,按照下面操作 return _numerical_gradient_no_batch(f, X) else: #否则按照多维操作 grad = np.zeros_like(X) for idx, x in enumerate(X): grad[idx] = _numerical_gradient_no_batch(f, x) return graddef _numerical_gradient_no_batch(f, x): h = 1e-4 # 0.0001 #提供一个很小的距离 grad = np.zeros_like(x) #zeros_like返回一个用0填充的跟输入数组形状和类型一样的数组。 for idx in range(x.size): #按照这个队列的长度进行轮询 tmp_val = x[idx] #取队列里面的数据,先是3,在是4 x[idx] = float(tmp_val) + h #为3+一个小的距离 fxh1 = f(x) # f(x+h) ,求函数在微调距离下的取值 x[idx] = tmp_val - h #为3减去一个小的距离 fxh2 = f(x) # f(x-h) ,求函数在微调距离下的取值 grad[idx] = (fxh1 - fxh2) / (2 * h) #求这两个距离下的取值 x[idx] = tmp_val #把数据返还给队列 return grad# coding: utf-8import numpy as npimport matplotlib.pylab as pltfrom gradient_2d import numerical_gradientdef gradient_descent(f, init_x, lr=0.01, step_num=100): x = init_x #为x 对象做初始化,队列np.array([-3.0,4.0]), x_history = [] #创建一个队列,为空 for i in range(step_num): x_history.append( x.copy() ) # numpy.copy(a, order='K', subok=False)[source] Return an array copy of the given object.返回对象的拷贝 grad = numerical_gradient(f, x) # 求函数的function_2()在[-3.0,4.0]的梯度。 x -= lr * grad #把x的数值做一个递减,减少grad的数值,这个 lr=0.1 ,grad 是上面函数输出的梯度值。(梯度值*小距离,理解就是逐渐的缩小位置了,这个grad 梯度其实也是个队列,比如说[3,2]) return x, np.array(x_history)def function_2(x): return x[0]**2 + x[1]**2init_x = np.array([-3.0, 4.0])lr = 0.1step_num = 20x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)plt.plot( [-5, 5], [0,0], '--b')plt.plot( [0,0], [-5, 5], '--b')plt.plot(x_history[:,0], x_history[:,1], 'o')plt.xlim(-3.5, 3.5)plt.ylim(-4.5, 4.5)plt.xlabel("X0")plt.ylabel("X1")plt.show() | 留言与评论(共有 0 条评论) “” |