梯度降低算法

  梯度降低法的简单介绍以及实现算法

  梯度降低法的基本思想能够类比为一个下山的过程。假设这样一个场景:一我的被困在山上,须要从山上下来(i.e.找到山的最低点,也就是山谷)。但此时山上的浓雾很大,致使可视度很低。所以,下山的路径就没法肯定,他必须利用本身周围的信息去找到下山的路径。这个时候,他就能够利用梯度降低算法来帮助本身下山。具体来讲就是,以他当前的所处的位置为基准,寻找这个位置最陡峭的地方,而后朝着山的高度降低的地方走,同理,若是咱们的目标是上山,也就是爬到山顶,那么此时应该是朝着最陡峭的方向往上走。而后每走一段距离,都反复采用同一个方法,最后就能成功的抵达山谷。app

  在这种就状况下,咱们也能够假设此时周围的陡峭程度咱们没法用肉眼来测量,须要一个复杂的工具来帮助咱们测量,恰巧的是此人正好拥有测量最陡峭方向的能力。所以,这我的每走一段距离,都须要一段时间来测量所在位置最陡峭的方向,这是比较耗时的。那么为了在太阳下山以前到达山底,就要尽量的减小测量方向的次数。这是一个两难的选择,若是测量的频繁,能够保证下山的方向是绝对正确的,但又很是耗时,若是测量的过少,又有偏离轨道的风险。因此须要找到一个合适的测量方向的频率,来确保下山的方向不错误,同时又不至于耗时太多!dom

  梯度降低ide

  梯度降低的过程就如同这个下山的场景同样函数

  首先,咱们有一个可微分的函数。这个函数就表明着一座山。咱们的目标就是找到这个函数的最小值,也就是山底。根据以前的场景假设,最快的下山的方式就是找到当前位置最陡峭的方向,而后沿着此方向向下走,对应到函数中,就是找到给定点的梯度 ,而后朝着梯度相反的方向,就能让函数值降低的最快!由于梯度的方向就是函数之变化最快的方向(在后面会详细解释)工具

  因此,咱们重复利用这个方法,反复求取梯度,最后就能到达局部的最小值,这就相似于咱们下山的过程。而求取梯度就肯定了最陡峭的方向,也就是场景中测量方向的手段。学习

  三种梯度算法的代码实现orm

  导入函数包it

  import osio

  %matplotlib inline

  import matplotlib as mpl

  import matplotlib.pyplot as plt

  import numpy as np

  批量梯度降低求解线性回归

  首先,咱们须要定义数据集和学习率 接下来咱们以矩阵向量的形式定义代价函数和代价函数的梯度 当循环次数超过1000次,这时候再继续迭代效果也不大了,因此这个时候能够退出循环!

  eta = 0.1

  n_iterations = 1000

  m = 100

  theta = np.random.randn(2, 1)

  for iteration in range(n_iterations): # 限定迭代次数

  gradients = 1/m * X_b.T.dot(X_b.dot(theta)-Y) # 梯度

  theta = theta - eta * gradients # 更新theta

  theta_path_bgd = []

  def plot_gradient_descent(theta, eta, theta_path = None):

  m = len(X_b)

  plt.plot(X, y, "b.")

  n_iterations = 1000

  for iteration in range(n_iterations):

  if iteration < 10: #取前十次

  y_predict = X_new_b.dot(theta)

  style = "b-"

  plt.plot(X_new,y_predict, style)

  gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)

  theta = theta - eta*gradients

  if theta_path is not None:

  theta_path.append(theta)

  plt.xlabel("$x_1$", fontsize=18)

  plt.axis([0, 2, 0, 15])

  plt.title(r"$\eta = {}$".format(eta),fontsize=16)

  np.random.seed(42) #随机数种子

  theta = np.random.randn(2,1) #random initialization

  plt.figure(figsize=(10,4))

  plt.subplot(131);plot_gradient_descent(theta, eta=0.02) # 第一个,

  plt.ylabel("$y$", rotation=0, fontsize=18)

  plt.subplot(132);plot_gradient_descent(theta, eta=0.1, theta_path=theta_path_bgd ) # 第二个,拟合最好,eta=0.1

  plt.subplot(133);plot_gradient_descent(theta, eta=0.5) # 第三个

  save_fig("gradient_descent_plot")

  运行结果

  随机梯度降低

  随机梯度降低每次用一个样原本梯度降低,可能获得局部最小值。

  theta_path_sgd = []

  m = len(X_b)

  np.random.seed(42)

  n_epochs = 50

  theta = np.random.randn(2,1) #随机初始化

  for epoch in range(n_epochs):

  for i in range(m):

  if epoch == 0 and i < 10:

  y_predict = X_new_b.dot(theta)

  style = "b-"

  plt.plot(X_new,y_predict,style)

  random_index = np.random.randint(m)

  xi = X_b[random_index:random_index+1]

  yi = y[random_index:random_index+1]

  gradients = 2 * xi.T.dot(xi.dot(theta)-yi)

  eta = 0.1

  theta = theta - eta * gradients

  theta_path_sgd.append(theta)

  plt.plot(x,y,"b.")

  plt.xlabel("$x_1$",fontsize = 18)

  plt.ylabel("$y$",rotation =0,fontsize = 18)

  plt.axis([0,2,0,15])

  save_fig("sgd_plot")

  plt.show()

  运行结果

  小批量梯度降低

  小批量梯度降低每次迭代使用一个以上又不是所有样本。

  theta_path_mgd = []

  n_iterations = 50

  minibatch_size = 20

  np.random.seed(42)

  theta = np.random.randn(2,1)

  for epoch in range(n_iterations):

  shuffled_indices = np.random.permutation(m)

  X_b_shuffled = X_b[shuffled_indices]

  y_shuffled = y[shuffled_indices]

  for i in range(0, m, minibatch_size):

  xi = X_b_shuffled[i:i+minibatch_size]

  yi = y_shuffled[i:i+minibatch_size]

  gradients = 2/minibatch_size * xi.T.dot(xi.dot(theta)-yi)

  eta = 0.1

  theta = theta-eta*gradients

  theta_path_mgd.append(theta)

  三者的比较图像

  theta_path_bgd = np.array(theta_path_bgd)

  theta_path_sgd = np.array(theta_path_sgd)

  theta_path_mgd = np.array(theta_path_mgd)

  plt.figure(figsize=(7,4))

  plt.plot(theta_path_sgd[:,0], theta_path_sgd[:,1], "r-s", linewidth = 1, label = "Stochastic")

  plt.plot(theta_path_mgd[:,0], theta_path_mgd[:,1], "g-+", linewidth = 2, label = "Mini-batch")

  plt.plot(theta_path_bgd[:,0], theta_path_bgd[:,1], "b-o", linewidth = 3, label = "Batch")

  plt.legend(loc="upper left", fontsize = 16)

  plt.xlabel(r"$\theta_0$", fontsize=20)

  plt.ylabel(r"$\theta_1$", fontsize=20, rotation=0)

  plt.axis([2.5,4.5,2.3,3.9])

  save_fig("gradients_descent_paths_plot")

  plt.show()

  运行结果

  总结:综合以上对比能够看出,批量梯度降低的准确度最好,其次是小批量梯度降低,最后是随机梯度降低。由于小批量梯度降低与随机梯度降低每次梯度估计的方向不肯定,可能须要很长时间接近最小值点。对于训练速度来讲,批量梯度降低在梯度降低的每一步中都用到了全部的训练样本,当样本量很大时,训练速度每每不能让人满意;随机梯度降低因为每次仅仅采用一个样原本迭代,因此训练速度很快;小批量

  梯度降低每次迭代使用一个以上又不是所有样本,所以训练速度介于二者之间。

相关文章
相关标签/搜索