标签:1.2 seed 增加 python 算法介绍 inf obj 分享图片 记录
1 import matplotlib.pyplot as plt 2 import numpy 3 4 5 class GD(object): 6 7 def __init__(self, seed=None, precision=1.E-6): 8 self.seed = GD.get_seed(seed) # 梯度下降算法的种子点 9 self.prec = precision # 梯度下降算法的计算精度 10 11 self.path = list() # 记录种子点的路径及相应的目标函数值 12 self.solve() # 求解主体 13 self.display() # 数据可视化展示 14 15 def solve(self): 16 x_curr = self.seed 17 val_curr = GD.func(*x_curr) 18 self.path.append((x_curr, val_curr)) 19 20 omega = 1 21 while omega > self.prec: 22 x_delta = omega * GD.get_grad(*x_curr) 23 x_next = x_curr - x_delta # 沿梯度反向迭代 24 val_next = GD.func(*x_next) 25 26 if numpy.abs(val_next - val_curr) < self.prec: 27 break 28 29 if val_next < val_curr: 30 x_curr = x_next 31 val_curr = val_next 32 omega *= 1.2 33 self.path.append((x_curr, val_curr)) 34 else: 35 omega *= 0.5 36 37 def display(self): 38 print(‘Iteration steps: {}‘.format(len(self.path))) 39 print(‘Seed: ({})‘.format(‘, ‘.join(str(item) for item in self.path[0][0]))) 40 print(‘Solution: ({})‘.format(‘, ‘.join(str(item) for item in self.path[-1][0]))) 41 42 fig = plt.figure(figsize=(10, 4)) 43 44 ax1 = plt.subplot(1, 2, 1) 45 ax2 = plt.subplot(1, 2, 2) 46 47 ax1.plot(numpy.array(range(len(self.path))) + 1, numpy.array(list(item[1] for item in self.path)), ‘k.‘) 48 ax1.plot(1, self.path[0][1], ‘go‘, label=‘starting point‘) 49 ax1.plot(len(self.path), self.path[-1][1], ‘r*‘, label=‘solution‘) 50 ax1.set(xlabel=‘$iterCnt$‘, ylabel=‘$iterVal$‘) 51 ax1.legend() 52 53 x = numpy.linspace(-100, 100, 500) 54 y = numpy.linspace(-100, 100, 500) 55 x, y = numpy.meshgrid(x, y) 56 z = GD.func(x, y) 57 ax2.contour(x, y, z, levels=36) 58 59 x2 = numpy.array(list(item[0][0] for item in self.path)) 60 y2 = numpy.array(list(item[0][1] for item in self.path)) 61 ax2.plot(x2, y2, ‘k--‘, linewidth=2) 62 ax2.plot(x2[0], y2[0], ‘go‘, label=‘starting point‘) 63 ax2.plot(x2[-1], y2[-1], ‘r*‘, label=‘solution‘) 64 65 ax2.set(xlabel=‘$x$‘, ylabel=‘$y$‘) 66 ax2.legend() 67 68 fig.tight_layout() 69 fig.savefig(‘test_plot.png‘, dpi=500) 70 71 plt.show() 72 plt.close() 73 74 # 内部种子生成函数 75 @staticmethod 76 def get_seed(seed): 77 if seed is not None: 78 return numpy.array(seed) 79 return numpy.random.uniform(-100, 100, 2) 80 81 # 目标函数 82 @staticmethod 83 def func(x, y): 84 return 5 * x ** 2 + 2 * y ** 2 + 3 * x - 10 * y + 4 85 86 # 目标函数的归一化梯度 87 @staticmethod 88 def get_grad(x, y): 89 grad_ori = numpy.array([10 * x + 3, 4 * y - 10]) 90 length = numpy.linalg.norm(grad_ori) 91 if length == 0: 92 return numpy.zeros(2) 93 return grad_ori / length 94 95 96 if __name__ == ‘__main__‘: 97 GD()
笔者所用示例函数为:
\begin{equation}
f(x, y) = 5x^2 + 2y^2 + 3x - 10y + 4
\end{equation}
标签:1.2 seed 增加 python 算法介绍 inf obj 分享图片 记录
原文地址:https://www.cnblogs.com/xxhbdk/p/10023110.html