从零开始使用 Nadam 进行梯度下降优化

开发 前端
梯度下降的局限性在于,如果梯度变为平坦或大曲率,搜索的进度可能会减慢。可以将动量添加到梯度下降中,该下降合并了一些惯性以进行更新。

[[394858]]

 梯度下降是一种优化算法,遵循目标函数的负梯度以定位函数的最小值。

梯度下降的局限性在于,如果梯度变为平坦或大曲率,搜索的进度可能会减慢。可以将动量添加到梯度下降中,该下降合并了一些惯性以进行更新。可以通过合并预计的新位置而非当前位置的梯度(称为Nesterov的加速梯度(NAG)或Nesterov动量)来进一步改善此效果。

梯度下降的另一个限制是,所有输入变量都使用单个步长(学习率)。对梯度下降的扩展,如自适应运动估计(Adam)算法,该算法对每个输入变量使用单独的步长,但可能会导致步长迅速减小到非常小的值。Nesterov加速的自适应矩估计或Nadam是Adam算法的扩展,该算法结合了Nesterov动量,可以使优化算法具有更好的性能。

在本教程中,您将发现如何从头开始使用Nadam进行梯度下降优化。完成本教程后,您将知道:

  • 梯度下降是一种优化算法,它使用目标函数的梯度来导航搜索空间。
  • 纳丹(Nadam)是亚当(Adam)版本的梯度下降的扩展,其中包括了内斯特罗夫的动量。
  • 如何从头开始实现Nadam优化算法并将其应用于目标函数并评估结果。

教程概述

本教程分为三个部分:他们是:

  • 梯度下降
  • Nadam优化算法
  • 娜达姆(Nadam)的梯度下降
    • 二维测试问题
    • Nadam的梯度下降优化
    • 可视化的Nadam优化

梯度下降

梯度下降是一种优化算法。它在技术上称为一阶优化算法,因为它明确利用了目标目标函数的一阶导数。

一阶导数,或简称为“导数”,是目标函数在特定点(例如,点)上的变化率或斜率。用于特定输入。

如果目标函数采用多个输入变量,则将其称为多元函数,并且可以将输入变量视为向量。反过来,多元目标函数的导数也可以视为向量,通常称为梯度。

梯度:多元目标函数的一阶导数。

对于特定输入,导数或梯度指向目标函数最陡峭的上升方向。梯度下降是指一种最小化优化算法,该算法遵循目标函数的下坡梯度负值来定位函数的最小值。

梯度下降算法需要一个正在优化的目标函数和该目标函数的导数函数。目标函数f()返回给定输入集合的分数,导数函数f'()给出给定输入集合的目标函数的导数。梯度下降算法需要问题中的起点(x),例如输入空间中的随机选择点。

假设我们正在最小化目标函数,然后计算导数并在输入空间中采取一步,这将导致目标函数下坡运动。首先通过计算输入空间中要移动多远的距离来进行下坡运动,计算方法是将步长(称为alpha或学习率)乘以梯度。然后从当前点减去该值,以确保我们逆梯度移动或向下移动目标函数。

  1. x(t)= x(t-1)–step* f'(x(t)) 

在给定点的目标函数越陡峭,梯度的大小越大,反过来,在搜索空间中采取的步伐也越大。使用步长超参数来缩放步长的大小。

步长:超参数,用于控制算法每次迭代相对于梯度在搜索空间中移动多远。

如果步长太小,则搜索空间中的移动将很小,并且搜索将花费很长时间。如果步长太大,则搜索可能会在搜索空间附近反弹并跳过最优值。

现在我们已经熟悉了梯度下降优化算法,接下来让我们看一下Nadam算法。

Nadam优化算法

Nesterov加速的自适应动量估计或Nadam算法是对自适应运动估计(Adam)优化算法的扩展,添加了Nesterov的加速梯度(NAG)或Nesterov动量,这是一种改进的动量。更广泛地讲,Nadam算法是对梯度下降优化算法的扩展。Timothy Dozat在2016年的论文“将Nesterov动量整合到Adam中”中描述了该算法。尽管论文的一个版本是在2015年以同名斯坦福项目报告的形式编写的。动量将梯度的指数衰减移动平均值(第一矩)添加到梯度下降算法中。这具有消除嘈杂的目标函数和提高收敛性的影响。Adam是梯度下降的扩展,它增加了梯度的第一和第二矩,并针对正在优化的每个参数自动调整学习率。NAG是动量的扩展,其中动量的更新是使用对参数的预计更新量而不是实际当前变量值的梯度来执行的。在某些情况下,这样做的效果是在找到最佳位置时减慢了搜索速度,而不是过冲。

纳丹(Nadam)是对亚当(Adam)的扩展,它使用NAG动量代替经典动量。让我们逐步介绍该算法的每个元素。Nadam使用衰减步长(alpha)和一阶矩(mu)超参数来改善性能。为了简单起见,我们暂时将忽略此方面,并采用恒定值。首先,对于搜索中要优化的每个参数,我们必须保持梯度的第一矩和第二矩,分别称为m和n。在搜索开始时将它们初始化为0.0。

  • m = 0
  • n = 0

该算法在从t = 1开始的时间t内迭代执行,并且每次迭代都涉及计算一组新的参数值x,例如。从x(t-1)到x(t)。如果我们专注于更新一个参数,这可能很容易理解该算法,该算法概括为通过矢量运算来更新所有参数。首先,计算当前时间步长的梯度(偏导数)。

  1. g(t)= f'(x(t-1)) 

接下来,使用梯度和超参数“ mu”更新第一时刻。

  1. m(t)=mu* m(t-1)+(1 –mu)* g(t) 

然后使用“ nu”超参数更新第二时刻。

  1. n(t)= nu * n(t-1)+(1 – nu)* g(t)^ 2 

接下来,使用Nesterov动量对第一时刻进行偏差校正。

  1. mhat =(mu * m(t)/(1 – mu))+((1 – mu)* g(t)/(1 – mu)) 

然后对第二个时刻进行偏差校正。注意:偏差校正是Adam的一个方面,它与在搜索开始时将第一时刻和第二时刻初始化为零这一事实相反。

  1. nhat = nu * n(t)/(1 – nu) 

最后,我们可以为该迭代计算参数的值。

  1. x(t)= x(t-1)– alpha /(sqrt(nhat)+ eps)* mhat 

其中alpha是步长(学习率)超参数,sqrt()是平方根函数,eps(epsilon)是一个较小的值,如1e-8,以避免除以零误差。

回顾一下,该算法有三个超参数。他们是:

  1. alpha:初始步长(学习率),典型值为0.002。 
  2. mu:第一时刻的衰减因子(Adam中的beta1),典型值为0.975。 
  3. nu:第二时刻的衰减因子(Adam中的beta2),典型值为0.999。 

就是这样。接下来,让我们看看如何在Python中从头开始实现该算法。

娜达姆(Nadam)的梯度下降

在本节中,我们将探索如何使用Nadam动量实现梯度下降优化算法。

二维测试问题

首先,让我们定义一个优化函数。我们将使用一个简单的二维函数,该函数将每个维的输入平方,并定义有效输入的范围(从-1.0到1.0)。下面的Objective()函数实现了此功能

  1. # objective function 
  2. def objective(x, y): 
  3.  return x**2.0 + y**2.0 

我们可以创建数据集的三维图,以了解响应面的曲率。下面列出了绘制目标函数的完整示例。

  1. # 3d plot of the test function 
  2. from numpy import arange 
  3. from numpy import meshgrid 
  4. from matplotlib import pyplot 
  5.   
  6. # objective function 
  7. def objective(x, y): 
  8.  return x**2.0 + y**2.0 
  9.   
  10. # define range for input 
  11. r_min, r_max = -1.0, 1.0 
  12. # sample input range uniformly at 0.1 increments 
  13. xaxis = arange(r_min, r_max, 0.1) 
  14. yaxis = arange(r_min, r_max, 0.1) 
  15. create a mesh from the axis 
  16. x, y = meshgrid(xaxis, yaxis) 
  17. # compute targets 
  18. results = objective(x, y) 
  19. create a surface plot with the jet color scheme 
  20. figure = pyplot.figure() 
  21. axis = figure.gca(projection='3d'
  22. axis.plot_surface(x, y, results, cmap='jet'
  23. # show the plot 
  24. pyplot.show() 

运行示例将创建目标函数的三维表面图。我们可以看到全局最小值为f(0,0)= 0的熟悉的碗形状。

我们还可以创建函数的二维图。这在以后要绘制搜索进度时会很有帮助。下面的示例创建目标函数的轮廓图。

  1. # contour plot of the test function 
  2. from numpy import asarray 
  3. from numpy import arange 
  4. from numpy import meshgrid 
  5. from matplotlib import pyplot 
  6.   
  7. # objective function 
  8. def objective(x, y): 
  9.  return x**2.0 + y**2.0 
  10.   
  11. # define range for input 
  12. bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) 
  13. # sample input range uniformly at 0.1 increments 
  14. xaxis = arange(bounds[0,0], bounds[0,1], 0.1) 
  15. yaxis = arange(bounds[1,0], bounds[1,1], 0.1) 
  16. create a mesh from the axis 
  17. x, y = meshgrid(xaxis, yaxis) 
  18. # compute targets 
  19. results = objective(x, y) 
  20. create a filled contour plot with 50 levels and jet color scheme 
  21. pyplot.contourf(x, y, results, levels=50, cmap='jet'
  22. # show the plot 
  23. pyplot.show() 

运行示例将创建目标函数的二维轮廓图。我们可以看到碗的形状被压缩为以颜色渐变显示的轮廓。我们将使用该图来绘制在搜索过程中探索的特定点。

现在我们有了一个测试目标函数,让我们看一下如何实现Nadam优化算法。

Nadam的梯度下降优化

我们可以将Nadam的梯度下降应用于测试问题。首先,我们需要一个函数来计算此函数的导数。

x ^ 2的导数在每个维度上均为x * 2。

  1. f(x)= x ^ 2 
  2. f'(x)= x * 2 

derived()函数在下面实现了这一点。

  1. # derivative of objective function 
  2. def derivative(x, y): 
  3.  return asarray([x * 2.0, y * 2.0]) 

接下来,我们可以使用Nadam实现梯度下降优化。首先,我们可以选择问题范围内的随机点作为搜索的起点。假定我们有一个数组,该数组定义搜索范围,每个维度一行,并且第一列定义最小值,第二列定义维度的最大值。

  1. # generate an initial point 
  2. x = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 
  3. score = objective(x[0], x[1]) 

接下来,我们需要初始化力矩矢量。

  1. # initialize decaying moving averages 
  2. m = [0.0 for _ in range(bounds.shape[0])] 
  3. n = [0.0 for _ in range(bounds.shape[0])] 

然后,我们运行由“ n_iter”超参数定义的算法的固定迭代次数。

  1. ... 
  2. # run iterations of gradient descent 
  3. for t in range(n_iter): 
  4.  ... 

第一步是计算当前参数集的导数。

  1. ... 
  2. # calculate gradient g(t) 
  3. g = derivative(x[0], x[1]) 

接下来,我们需要执行Nadam更新计算。为了提高可读性,我们将使用命令式编程样式来一次执行一个变量的这些计算。在实践中,我建议使用NumPy向量运算以提高效率。

  1. ... 
  2. # build a solution one variable at a time 
  3. for i in range(x.shape[0]): 
  4.  ... 

首先,我们需要计算力矩矢量。

  1. # m(t) = mu * m(t-1) + (1 - mu) * g(t) 
  2. m[i] = mu * m[i] + (1.0 - mu) * g[i] 

然后是第二个矩向量。

  1. # nhat = nu * n(t) / (1 - nu) 
  2. nhat = nu * n[i] / (1.0 - nu) 
  3. # n(t) = nu * n(t-1) + (1 - nu) * g(t)^2 
  4. n[i] = nu * n[i] + (1.0 - nu) * g[i]**2 

然后是经过偏差校正的内斯特罗夫动量。

  1. # mhat = (mu * m(t) / (1 - mu)) + ((1 - mu) * g(t) / (1 - mu)) 
  2. mhat = (mu * m[i] / (1.0 - mu)) + ((1 - mu) * g[i] / (1.0 - mu)) 

偏差校正的第二时刻。

  1. # nhat = nu * n(t) / (1 - nu) 
  2. nhat = nu * n[i] / (1.0 - nu) 

最后更新参数。

  1. # x(t) = x(t-1) - alpha / (sqrt(nhat) + eps) * mhat 
  2. x[i] = x[i] - alpha / (sqrt(nhat) + eps) * mhat 

然后,针对要优化的每个参数重复此操作。在迭代结束时,我们可以评估新的参数值并报告搜索的性能。

  1. # evaluate candidate point 
  2. score = objective(x[0], x[1]) 
  3. # report progress 
  4. print('>%d f(%s) = %.5f' % (t, x, score)) 

我们可以将所有这些结合到一个名为nadam()的函数中,该函数采用目标函数和派生函数的名称以及算法超参数,并返回在搜索及其评估结束时找到的最佳解决方案。

  1. # gradient descent algorithm with nadam 
  2. def nadam(objective, derivative, bounds, n_iter, alpha, mu, nu, eps=1e-8): 
  3.  # generate an initial point 
  4.  x = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 
  5.  score = objective(x[0], x[1]) 
  6.  # initialize decaying moving averages 
  7.  m = [0.0 for _ in range(bounds.shape[0])] 
  8.  n = [0.0 for _ in range(bounds.shape[0])] 
  9.  # run the gradient descent 
  10.  for t in range(n_iter): 
  11.   # calculate gradient g(t) 
  12.   g = derivative(x[0], x[1]) 
  13.   # build a solution one variable at a time 
  14.   for i in range(bounds.shape[0]): 
  15.    # m(t) = mu * m(t-1) + (1 - mu) * g(t) 
  16.    m[i] = mu * m[i] + (1.0 - mu) * g[i] 
  17.    # n(t) = nu * n(t-1) + (1 - nu) * g(t)^2 
  18.    n[i] = nu * n[i] + (1.0 - nu) * g[i]**2 
  19.    # mhat = (mu * m(t) / (1 - mu)) + ((1 - mu) * g(t) / (1 - mu)) 
  20.    mhat = (mu * m[i] / (1.0 - mu)) + ((1 - mu) * g[i] / (1.0 - mu)) 
  21.    # nhat = nu * n(t) / (1 - nu) 
  22.    nhat = nu * n[i] / (1.0 - nu) 
  23.    # x(t) = x(t-1) - alpha / (sqrt(nhat) + eps) * mhat 
  24.    x[i] = x[i] - alpha / (sqrt(nhat) + eps) * mhat 
  25.   # evaluate candidate point 
  26.   score = objective(x[0], x[1]) 
  27.   # report progress 
  28.   print('>%d f(%s) = %.5f' % (t, x, score)) 
  29.  return [x, score] 

然后,我们可以定义函数和超参数的界限,并调用函数执行优化。在这种情况下,我们将运行该算法进行50次迭代,初始alpha为0.02,μ为0.8,nu为0.999,这是经过一点点反复试验后发现的。

  1. # seed the pseudo random number generator 
  2. seed(1) 
  3. # define range for input 
  4. bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) 
  5. # define the total iterations 
  6. n_iter = 50 
  7. # steps size 
  8. alpha = 0.02 
  9. # factor for average gradient 
  10. mu = 0.8 
  11. # factor for average squared gradient 
  12. nu = 0.999 
  13. # perform the gradient descent search with nadam 
  14. best, score = nadam(objective, derivative, bounds, n_iter, alpha, mu, nu) 

运行结束时,我们将报告找到的最佳解决方案。

  1. # summarize the result 
  2. print('Done!'
  3. print('f(%s) = %f' % (best, score)) 

综合所有这些,下面列出了适用于我们的测试问题的Nadam梯度下降的完整示例。

  1. # gradient descent optimization with nadam for a two-dimensional test function 
  2. from math import sqrt 
  3. from numpy import asarray 
  4. from numpy.random import rand 
  5. from numpy.random import seed 
  6.   
  7. # objective function 
  8. def objective(x, y): 
  9.  return x**2.0 + y**2.0 
  10.   
  11. # derivative of objective function 
  12. def derivative(x, y): 
  13.  return asarray([x * 2.0, y * 2.0]) 
  14.   
  15. # gradient descent algorithm with nadam 
  16. def nadam(objective, derivative, bounds, n_iter, alpha, mu, nu, eps=1e-8): 
  17.  # generate an initial point 
  18.  x = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 
  19.  score = objective(x[0], x[1]) 
  20.  # initialize decaying moving averages 
  21.  m = [0.0 for _ in range(bounds.shape[0])] 
  22.  n = [0.0 for _ in range(bounds.shape[0])] 
  23.  # run the gradient descent 
  24.  for t in range(n_iter): 
  25.   # calculate gradient g(t) 
  26.   g = derivative(x[0], x[1]) 
  27.   # build a solution one variable at a time 
  28.   for i in range(bounds.shape[0]): 
  29.    # m(t) = mu * m(t-1) + (1 - mu) * g(t) 
  30.    m[i] = mu * m[i] + (1.0 - mu) * g[i] 
  31.    # n(t) = nu * n(t-1) + (1 - nu) * g(t)^2 
  32.    n[i] = nu * n[i] + (1.0 - nu) * g[i]**2 
  33.    # mhat = (mu * m(t) / (1 - mu)) + ((1 - mu) * g(t) / (1 - mu)) 
  34.    mhat = (mu * m[i] / (1.0 - mu)) + ((1 - mu) * g[i] / (1.0 - mu)) 
  35.    # nhat = nu * n(t) / (1 - nu) 
  36.    nhat = nu * n[i] / (1.0 - nu) 
  37.    # x(t) = x(t-1) - alpha / (sqrt(nhat) + eps) * mhat 
  38.    x[i] = x[i] - alpha / (sqrt(nhat) + eps) * mhat 
  39.   # evaluate candidate point 
  40.   score = objective(x[0], x[1]) 
  41.   # report progress 
  42.   print('>%d f(%s) = %.5f' % (t, x, score)) 
  43.  return [x, score] 
  44.   
  45. # seed the pseudo random number generator 
  46. seed(1) 
  47. # define range for input 
  48. bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) 
  49. # define the total iterations 
  50. n_iter = 50 
  51. # steps size 
  52. alpha = 0.02 
  53. # factor for average gradient 
  54. mu = 0.8 
  55. # factor for average squared gradient 
  56. nu = 0.999 
  57. # perform the gradient descent search with nadam 
  58. best, score = nadam(objective, derivative, bounds, n_iter, alpha, mu, nu) 
  59. print('Done!'
  60. print('f(%s) = %f' % (best, score)) 

运行示例将优化算法和Nadam应用于我们的测试问题,并报告算法每次迭代的搜索性能。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到在大约44次搜索迭代后找到了接近最佳的解决方案,输入值接近0.0和0.0,评估为0.0。

  1. >40 f([ 5.07445337e-05 -3.32910019e-03]) = 0.00001 
  2. >41 f([-1.84325171e-05 -3.00939427e-03]) = 0.00001 
  3. >42 f([-6.78814472e-05 -2.69839367e-03]) = 0.00001 
  4. >43 f([-9.88339249e-05 -2.40042096e-03]) = 0.00001 
  5. >44 f([-0.00011368 -0.00211861]) = 0.00000 
  6. >45 f([-0.00011547 -0.00185511]) = 0.00000 
  7. >46 f([-0.0001075 -0.00161122]) = 0.00000 
  8. >47 f([-9.29922627e-05 -1.38760991e-03]) = 0.00000 
  9. >48 f([-7.48258406e-05 -1.18436586e-03]) = 0.00000 
  10. >49 f([-5.54299505e-05 -1.00116899e-03]) = 0.00000 
  11. Done! 
  12. f([-5.54299505e-05 -1.00116899e-03]) = 0.000001 

可视化的Nadam优化

我们可以在域的等高线上绘制Nadam搜索的进度。这可以为算法迭代过程中的搜索进度提供直观的认识。我们必须更新nadam()函数以维护在搜索过程中找到的所有解决方案的列表,然后在搜索结束时返回此列表。下面列出了具有这些更改的功能的更新版本。

  1. # gradient descent algorithm with nadam 
  2. def nadam(objective, derivative, bounds, n_iter, alpha, mu, nu, eps=1e-8): 
  3.  solutions = list() 
  4.  # generate an initial point 
  5.  x = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 
  6.  score = objective(x[0], x[1]) 
  7.  # initialize decaying moving averages 
  8.  m = [0.0 for _ in range(bounds.shape[0])] 
  9.  n = [0.0 for _ in range(bounds.shape[0])] 
  10.  # run the gradient descent 
  11.  for t in range(n_iter): 
  12.   # calculate gradient g(t) 
  13.   g = derivative(x[0], x[1]) 
  14.   # build a solution one variable at a time 
  15.   for i in range(bounds.shape[0]): 
  16.    # m(t) = mu * m(t-1) + (1 - mu) * g(t) 
  17.    m[i] = mu * m[i] + (1.0 - mu) * g[i] 
  18.    # n(t) = nu * n(t-1) + (1 - nu) * g(t)^2 
  19.    n[i] = nu * n[i] + (1.0 - nu) * g[i]**2 
  20.    # mhat = (mu * m(t) / (1 - mu)) + ((1 - mu) * g(t) / (1 - mu)) 
  21.    mhat = (mu * m[i] / (1.0 - mu)) + ((1 - mu) * g[i] / (1.0 - mu)) 
  22.    # nhat = nu * n(t) / (1 - nu) 
  23.    nhat = nu * n[i] / (1.0 - nu) 
  24.    # x(t) = x(t-1) - alpha / (sqrt(nhat) + eps) * mhat 
  25.    x[i] = x[i] - alpha / (sqrt(nhat) + eps) * mhat 
  26.   # evaluate candidate point 
  27.   score = objective(x[0], x[1]) 
  28.   # store solution 
  29.   solutions.append(x.copy()) 
  30.   # report progress 
  31.   print('>%d f(%s) = %.5f' % (t, x, score)) 
  32.  return solutions 

然后,我们可以像以前一样执行搜索,这一次将检索解决方案列表,而不是最佳的最终解决方案。

  1. # seed the pseudo random number generator 
  2. seed(1) 
  3. # define range for input 
  4. bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) 
  5. # define the total iterations 
  6. n_iter = 50 
  7. # steps size 
  8. alpha = 0.02 
  9. # factor for average gradient 
  10. mu = 0.8 
  11. # factor for average squared gradient 
  12. nu = 0.999 
  13. # perform the gradient descent search with nadam 
  14. solutions = nadam(objective, derivative, bounds, n_iter, alpha, mu, nu) 

然后,我们可以像以前一样创建目标函数的轮廓图。

  1. # sample input range uniformly at 0.1 increments 
  2. xaxis = arange(bounds[0,0], bounds[0,1], 0.1) 
  3. yaxis = arange(bounds[1,0], bounds[1,1], 0.1) 
  4. create a mesh from the axis 
  5. x, y = meshgrid(xaxis, yaxis) 
  6. # compute targets 
  7. results = objective(x, y) 
  8. create a filled contour plot with 50 levels and jet color scheme 
  9. pyplot.contourf(x, y, results, levels=50, cmap='jet'

最后,我们可以将在搜索过程中找到的每个解决方案绘制成一条由一条线连接的白点。

  1. # plot the sample as black circles 
  2. solutions = asarray(solutions) 
  3. pyplot.plot(solutions[:, 0], solutions[:, 1], '.-', color='w'

综上所述,下面列出了对测试问题执行Nadam优化并将结果绘制在轮廓图上的完整示例。

  1. # example of plotting the nadam search on a contour plot of the test function 
  2. from math import sqrt 
  3. from numpy import asarray 
  4. from numpy import arange 
  5. from numpy import product 
  6. from numpy.random import rand 
  7. from numpy.random import seed 
  8. from numpy import meshgrid 
  9. from matplotlib import pyplot 
  10. from mpl_toolkits.mplot3d import Axes3D 
  11.   
  12. # objective function 
  13. def objective(x, y): 
  14.  return x**2.0 + y**2.0 
  15.   
  16. # derivative of objective function 
  17. def derivative(x, y): 
  18.  return asarray([x * 2.0, y * 2.0]) 
  19.   
  20. # gradient descent algorithm with nadam 
  21. def nadam(objective, derivative, bounds, n_iter, alpha, mu, nu, eps=1e-8): 
  22.  solutions = list() 
  23.  # generate an initial point 
  24.  x = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0]) 
  25.  score = objective(x[0], x[1]) 
  26.  # initialize decaying moving averages 
  27.  m = [0.0 for _ in range(bounds.shape[0])] 
  28.  n = [0.0 for _ in range(bounds.shape[0])] 
  29.  # run the gradient descent 
  30.  for t in range(n_iter): 
  31.   # calculate gradient g(t) 
  32.   g = derivative(x[0], x[1]) 
  33.   # build a solution one variable at a time 
  34.   for i in range(bounds.shape[0]): 
  35.    # m(t) = mu * m(t-1) + (1 - mu) * g(t) 
  36.    m[i] = mu * m[i] + (1.0 - mu) * g[i] 
  37.    # n(t) = nu * n(t-1) + (1 - nu) * g(t)^2 
  38.    n[i] = nu * n[i] + (1.0 - nu) * g[i]**2 
  39.    # mhat = (mu * m(t) / (1 - mu)) + ((1 - mu) * g(t) / (1 - mu)) 
  40.    mhat = (mu * m[i] / (1.0 - mu)) + ((1 - mu) * g[i] / (1.0 - mu)) 
  41.    # nhat = nu * n(t) / (1 - nu) 
  42.    nhat = nu * n[i] / (1.0 - nu) 
  43.    # x(t) = x(t-1) - alpha / (sqrt(nhat) + eps) * mhat 
  44.    x[i] = x[i] - alpha / (sqrt(nhat) + eps) * mhat 
  45.   # evaluate candidate point 
  46.   score = objective(x[0], x[1]) 
  47.   # store solution 
  48.   solutions.append(x.copy()) 
  49.   # report progress 
  50.   print('>%d f(%s) = %.5f' % (t, x, score)) 
  51.  return solutions 
  52.   
  53. # seed the pseudo random number generator 
  54. seed(1) 
  55. # define range for input 
  56. bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) 
  57. # define the total iterations 
  58. n_iter = 50 
  59. # steps size 
  60. alpha = 0.02 
  61. # factor for average gradient 
  62. mu = 0.8 
  63. # factor for average squared gradient 
  64. nu = 0.999 
  65. # perform the gradient descent search with nadam 
  66. solutions = nadam(objective, derivative, bounds, n_iter, alpha, mu, nu) 
  67. # sample input range uniformly at 0.1 increments 
  68. xaxis = arange(bounds[0,0], bounds[0,1], 0.1) 
  69. yaxis = arange(bounds[1,0], bounds[1,1], 0.1) 
  70. create a mesh from the axis 
  71. x, y = meshgrid(xaxis, yaxis) 
  72. # compute targets 
  73. results = objective(x, y) 
  74. create a filled contour plot with 50 levels and jet color scheme 
  75. pyplot.contourf(x, y, results, levels=50, cmap='jet'
  76. # plot the sample as black circles 
  77. solutions = asarray(solutions) 
  78. pyplot.plot(solutions[:, 0], solutions[:, 1], '.-', color='w'
  79. # show the plot 
  80. pyplot.show() 

运行示例将像以前一样执行搜索,但是在这种情况下,将创建目标函数的轮廓图。

在这种情况下,我们可以看到在搜索过程中找到的每个解决方案都显示一个白点,从最优点开始,逐渐靠近图中心的最优点。

 

责任编辑:武晓燕 来源: Python中文社区
相关推荐

2018-05-09 20:08:09

人工智能深度学习Python

2017-06-29 11:05:46

TensorFlow深度学习

2022-01-24 07:35:39

XLL网络攻击恶意软件

2020-07-02 15:32:23

Kubernetes容器架构

2019-01-18 12:39:45

云计算PaaS公有云

2018-04-18 07:01:59

Docker容器虚拟机

2015-11-17 16:11:07

Code Review

2013-09-22 10:15:01

Spring DataJPA

2019-09-30 10:51:11

Markdown标记语言

2010-05-26 17:35:08

配置Xcode SVN

2018-09-14 17:16:22

云计算软件计算机网络

2023-12-27 08:47:41

PrometheusLinux架构

2018-03-14 11:15:06

2017-10-05 16:51:28

LSTM神经网络货币兑换汇率

2021-03-23 15:35:36

Adam优化语言

2017-08-25 14:29:43

机器学习Java

2015-10-15 14:16:24

2011-04-06 15:55:50

开发webOS程序webOS

2024-04-10 07:48:41

搜索引擎场景

2022-06-09 09:00:00

编程语言后端Dark
点赞
收藏

51CTO技术栈公众号