脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python+numpy+matplotalib实现梯度下降法

python+numpy+matplotalib实现梯度下降法

2021-03-31 00:10Cludy_Sky Python

这篇文章主要为大家详细介绍了python+numpy+matplotalib实现梯度下降法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

这个阶段一直在做和梯度一类算法相关的东西,索性在这儿做个汇总,

一、算法论述

梯度下降法(gradient  descent)别名最速下降法(曾经我以为这是两个不同的算法-.-),是用来求解无约束最优化问题的一种常用算法。下面以求解线性回归为题来叙述:

设:一般的线性回归方程(拟合函数)为:(其中python+numpy+matplotalib实现梯度下降法的值为1)

python+numpy+matplotalib实现梯度下降法  

python+numpy+matplotalib实现梯度下降法这一组向量参数选择的好与坏就需要一个机制来评估,据此我们提出了其损失函数为(选择均方误差):

python+numpy+matplotalib实现梯度下降法

我们现在的目的就是使得损失函数python+numpy+matplotalib实现梯度下降法取得最小值,即目标函数为:

python+numpy+matplotalib实现梯度下降法

如果python+numpy+matplotalib实现梯度下降法的值取到了0,意味着我们构造出了极好的拟合函数,也即选择出了最好的python+numpy+matplotalib实现梯度下降法值,但这基本是达不到的,我们只能使得其无限的接近于0,当满足一定精度时停止迭代。

那么问题来了如何调整python+numpy+matplotalib实现梯度下降法使得python+numpy+matplotalib实现梯度下降法取得的值越来越小呢?方法很多,此处以梯度下降法为例:

分为两步:(1)初始化python+numpy+matplotalib实现梯度下降法的值。

                  (2)改变python+numpy+matplotalib实现梯度下降法的值,使得python+numpy+matplotalib实现梯度下降法按梯度下降的方向减少。

python+numpy+matplotalib实现梯度下降法值的更新使用如下的方式来完成:

python+numpy+matplotalib实现梯度下降法

  python+numpy+matplotalib实现梯度下降法      

其中python+numpy+matplotalib实现梯度下降法为步长因子,这里我们取定值,但注意如果python+numpy+matplotalib实现梯度下降法取得过小会导致收敛速度过慢,python+numpy+matplotalib实现梯度下降法过大则损失函数可能不会收敛,甚至逐渐变大,可以在下述的代码中修改python+numpy+matplotalib实现梯度下降法的值来进行验证。后面我会再写一篇关于随机梯度下降法的文章,其实与梯度下降法最大的不同就在于一个求和符号。

二、代码实现

python" id="highlighter_837694">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import style
 
 
#构造数据
def get_data(sample_num=10000):
  """
  拟合函数为
  y = 5*x1 + 7*x2
  :return:
  """
  x1 = np.linspace(0, 9, sample_num)
  x2 = np.linspace(4, 13, sample_num)
  x = np.concatenate(([x1], [x2]), axis=0).t
  y = np.dot(x, np.array([5, 7]).t)
  return x, y
#梯度下降法
def gd(samples, y, step_size=0.01, max_iter_count=1000):
  """
  :param samples: 样本
  :param y: 结果value
  :param step_size: 每一接迭代的步长
  :param max_iter_count: 最大的迭代次数
  :param batch_size: 随机选取的相对于总样本的大小
  :return:
  """
  #确定样本数量以及变量的个数初始化theta值
  m, var = samples.shape
  theta = np.zeros(2)
  y = y.flatten()
  #进入循环内
  print(samples)
  loss = 1
  iter_count = 0
  iter_list=[]
  loss_list=[]
  theta1=[]
  theta2=[]
  #当损失精度大于0.01且迭代此时小于最大迭代次数时,进行
  while loss > 0.001 and iter_count < max_iter_count:
    loss = 0
    #梯度计算
    theta1.append(theta[0])
    theta2.append(theta[1])
    for i in range(m):
      h = np.dot(theta,samples[i].t) 
    #更新theta的值,需要的参量有:步长,梯度
      for j in range(len(theta)):
        theta[j] = theta[j] - step_size*(1/m)*(h - y[i])*samples[i,j]
    #计算总体的损失精度,等于各个样本损失精度之和
    for i in range(m):
      h = np.dot(theta.t, samples[i])
      #每组样本点损失的精度
      every_loss = (1/(var*m))*np.power((h - y[i]), 2)
      loss = loss + every_loss
 
    print("iter_count: ", iter_count, "the loss:", loss)
    
    iter_list.append(iter_count)
    loss_list.append(loss)
    
    iter_count += 1
  plt.plot(iter_list,loss_list)
  plt.xlabel("iter")
  plt.ylabel("loss")
  plt.show()
  return theta1,theta2,theta,loss_list
def painter3d(theta1,theta2,loss):
  style.use('ggplot')
  fig = plt.figure()
  ax1 = fig.add_subplot(111, projection='3d')
  x,y,z = theta1,theta2,loss
  ax1.plot_wireframe(x,y,z, rstride=5, cstride=5)
  ax1.set_xlabel("theta1")
  ax1.set_ylabel("theta2")
  ax1.set_zlabel("loss")
  plt.show()
def predict(x, theta):
  y = np.dot(theta, x.t)
  return y   
if __name__ == '__main__':
  samples, y = get_data()
  theta1,theta2,theta,loss_list = gd(samples, y)
  print(theta) # 会很接近[5, 7]
  painter3d(theta1,theta2,loss_list)
  predict_y = predict(theta, [7,8])
  print(predict_y)

三、绘制的图像如下:

迭代次数与损失精度间的关系图如下:步长为0.01

python+numpy+matplotalib实现梯度下降法

变量python+numpy+matplotalib实现梯度下降法python+numpy+matplotalib实现梯度下降法与损失函数loss之间的关系:(从初始化之后会一步步收敛到loss满足精度,之后python+numpy+matplotalib实现梯度下降法python+numpy+matplotalib实现梯度下降法会变的稳定下来)

python+numpy+matplotalib实现梯度下降法

下面我们来看一副当步长因子变大后的图像:步长因子为0.5(很明显其收敛速度变缓了)

python+numpy+matplotalib实现梯度下降法

python+numpy+matplotalib实现梯度下降法

当步长因子设置为1.8左右时,其损失值已经开始震荡

python+numpy+matplotalib实现梯度下降法

          python+numpy+matplotalib实现梯度下降法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/m2284089331/article/details/76397658

延伸 · 阅读

精彩推荐