何为梯度下降,直白点就是,链式求导法则,不断更新变量值。

这里讲解的代码为李宏毅老师机器学习课程中 class 4 回归展示 中的代码demo
 

Loss函数

python代码如下

import numpy as np
import matplotlib.pyplot as plt # y_data = b + w * x_data
x_data = [338., 333., 328., 207., 226., 25., 179., 60., 208., 606.] # 10 个数
y_data = [640., 633., 619., 393., 428., 27., 193., 66., 226., 1591.] # 10 个数 x = np.arange(-200, -100, 1) # bias
y = np.arange(-5, 5, 0.1) # weight
z = np.zeros((len(x), len(y))) # zeros函数表示输出的数组为 100行 100列 #X, Y = np.meshgrid(x, y) 个人感觉这句话没用。。。 for i in range(len(x)):
for j in range(len(y)):
b = x[i]
w = y[j]
z[j][i] = 0
for n in range(len(x_data)):
# z[j][i]为 b=x[i] 及 w=y[j] 时,对应的 Loss Function 的大小
z[j][i] = z[j][i] + (y_data[n] - b - w * x_data[n]) ** 2
z[j][i] = z[j][i] / len(x_data) # 求 loss function 均值 # y_data = b + w * x_data
b = -120 # initial b
w = -4 # initial w
lr = 0.0000001 # learning rate
iteration = 100000 # 迭代运行次数 # store initial values for plotting
b_history = [b]
w_history = [w] # iterations
for i in range(iteration): # 在 100000 次迭代下,看最后结果
b_grad = 0.0 # 对 b_grad 重新赋值为0
w_grad = 0.0 # 对 w_grad 重新赋值为0
for n in range(len(x_data)):
# 此处应该注意的是,求导的是Loss函数,因此对应的变量是w、b,是看w、b在各自的轴上的移动
b_grad = b_grad + 2.0 * (y_data[n] - b - w * x_data[n]) * ( - 1.0)
w_grad = w_grad + 2.0 * (y_data[n] - b - w * x_data[n]) * ( - x_data[n]) # update parameters
b = b - lr * b_grad
w = w - lr * w_grad # store parameters for plotting
b_history.append(b)
w_history.append(w) # plot the figure
plt.contourf(x, y, z, 50, alpha = 0.5, cmap = plt.get_cmap('jet'))
plt.plot([-188.4], [2.67], 'x', ms = 12, markeredgewidth = 3, color = 'orange')
plt.plot(b_history, w_history, 'o-', ms = 3, lw = 1.5, color = 'black')
plt.xlim(-200, -100)
plt.ylim(-5, 5)
plt.xlabel(r'$b$', fontsize=16)
plt.ylabel(r'$w$', fontsize=16)
plt.show()

当learning rate 即 lr = 0.0000001时

当learning rate 即 lr = 0.000001时

learning rate 即 lr = 0.00001时

可以看到效果不是很好 所以改变learning rate

import numpy as np
import matplotlib.pyplot as plt # y_data = b + w * x_data
x_data = [338., 333., 328., 207., 226., 25., 179., 60., 208., 606.] # 10 个数
y_data = [640., 633., 619., 393., 428., 27., 193., 66., 226., 1591.] # 10 个数 x = np.arange(-200, -100, 1) # bias
y = np.arange(-5, 5, 0.1) # weight
z = np.zeros((len(x), len(y))) # zeros函数表示输出的数组为 100 行 100 列 # X, Y = np.meshgrid(x, y) for i in range(len(x)):
for j in range(len(y)):
b = x[i]
w = y[j]
z[j][i] = 0
for n in range(len(x_data)):
# z[j][i]为 b=x[i] 及 w=y[j] 时,对应的 Loss Function 的大小
z[j][i] = z[j][i] + (y_data[n] - b - w * x_data[n]) ** 2
z[j][i] = z[j][i] / len(x_data) # 求 loss function 均值 # ydata = b + w * xdata
b = -120 # initial b
w = -4 # initial w
lr = 1 # learning rate
iteration = 100000 # 迭代运行次数 # store initial values for plotting
b_history = [b]
w_history = [w] # 个性化 w 和 b 的 learning rate
lr_b = 0
lr_w = 0 # iterations
for i in range(iteration): # 在 100000 次迭代下,看最后结果
b_grad = 0.0 # 对 b_grad 重新赋值为0
w_grad = 0.0 # 对 w_grad 重新赋值为0
for n in range(len(x_data)):
# 此处应该注意的是,求导的是L函数,因此对应的变量是w、b,是看w、b在各自的轴上的移动
b_grad = b_grad + 2.0 * (y_data[n] - b - w * x_data[n]) * (- 1.0)
w_grad = w_grad + 2.0 * (y_data[n] - b - w * x_data[n]) * (- x_data[n]) lr_b = lr_b + b_grad ** 2
lr_w = lr_w + w_grad ** 2 # update parameters
b = b - lr / np.sqrt(lr_b) * b_grad
w = w - lr / np.sqrt(lr_w) * w_grad # store parameters for plotting
b_history.append(b)
w_history.append(w) # plot the figure
plt.contourf(x, y, z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))
plt.plot([-188.4], [2.67], 'x', ms=12, markeredgewidth=3, color='orange')
plt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')
plt.xlim(-200, -100)
plt.ylim(-5, 5)
plt.xlabel(r'$b$', fontsize=16)
plt.ylabel(r'$w$', fontsize=16)
plt.show()

结果展示

一些说明:

np.array np.asarray的区别

array和asarry都可以将结构数据转换为ndarray类型

但是主要的区别在于当数据源是ndarray时,array仍会copy出一个副本,占用新的内存,但asarray不会。

np.meshgrid的作用

生成网格点坐标矩阵

 

李宏毅 Gradient Descent Demo 代码讲解的更多相关文章

  1. 几种梯度下降方法对比(Batch gradient descent、Mini-batch gradient descent 和 stochastic gradient descent)

    https://blog.csdn.net/u012328159/article/details/80252012 我们在训练神经网络模型时,最常用的就是梯度下降,这篇博客主要介绍下几种梯度下降的变种 ...

  2. 李宏毅机器学习笔记2:Gradient Descent(附带详细的原理推导过程)

    李宏毅老师的机器学习课程和吴恩达老师的机器学习课程都是都是ML和DL非常好的入门资料,在YouTube.网易云课堂.B站都能观看到相应的课程视频,接下来这一系列的博客我都将记录老师上课的笔记以及自己对 ...

  3. 李宏毅机器学习课程---4、Gradient Descent (如何优化 )

    李宏毅机器学习课程---4.Gradient Descent (如何优化) 一.总结 一句话总结: 调整learning rates:Tuning your learning rates 随机Grad ...

  4. Logistic Regression Using Gradient Descent -- Binary Classification 代码实现

    1. 原理 Cost function Theta 2. Python # -*- coding:utf8 -*- import numpy as np import matplotlib.pyplo ...

  5. Linear Regression Using Gradient Descent 代码实现

    参考吴恩达<机器学习>, 进行 Octave, Python(Numpy), C++(Eigen) 的原理实现, 同时用 scikit-learn, TensorFlow, dlib 进行 ...

  6. 【笔记】机器学习 - 李宏毅 - 4 - Gradient Descent

    梯度下降 Gradient Descent 梯度下降是一种迭代法(与最小二乘法不同),目标是解决最优化问题:\({\theta}^* = arg min_{\theta} L({\theta})\), ...

  7. 【论文翻译】An overiview of gradient descent optimization algorithms

    这篇论文最早是一篇2016年1月16日发表在Sebastian Ruder的博客.本文主要工作是对这篇论文与李宏毅课程相关的核心部分进行翻译. 论文全文翻译: An overview of gradi ...

  8. 梯度下降算法实现原理(Gradient Descent)

    概述   梯度下降法(Gradient Descent)是一个算法,但不是像多元线性回归那样是一个具体做回归任务的算法,而是一个非常通用的优化算法来帮助一些机器学习算法求解出最优解的,所谓的通用就是很 ...

  9. 梯度下降(Gradient Descent)小结

    在求解机器学习算法的模型参数,即无约束优化问题时,梯度下降(Gradient Descent)是最常采用的方法之一,另一种常用的方法是最小二乘法.这里就对梯度下降法做一个完整的总结. 1. 梯度 在微 ...

随机推荐

  1. Lighting Techinology of the Last Of Us (2013 SIGGRAPH)

    Lighting Techinology of the Last Of Us(2013 SIGGRAPH) or "Old Lightmaps - New Tricks" 原作:M ...

  2. 部署lnmp

    装包 1.安装依赖包 yum - y install gcc openssl-devel pcre-devel zlib-devel 2.解源码包 .tar.gz 3.切换到解压缩后的目录,配置参数 ...

  3. Visual Studio 2019 激活

    Visual Studio 2019 Enterprise 企业版:BF8Y8-GN2QH-T84XB-QVY3B-RC4DF Visual Studio 2019 Professional 专业版: ...

  4. msyql round函数隐藏问题

    1.背景 在用mysql round进行四舍五入计算的时候如果参与计算的字段为float,则最终计算出的四舍五入效果会有很大出入.例子我就不列举了 2.原因 mysql官方文档中关于ROUND函数的部 ...

  5. plupload+上传文件夹

    文件夹数据库处理逻辑 publicclass DbFolder { JSONObject root; public DbFolder() { this.root = new JSONObject(); ...

  6. (五)CWnd 所有窗口类的父类,CFrameWnd,Afx_xxx 全局函数,命名规范

    CWnd::MessageBox: 只有CWnd的派生类才可以使用MessageBox 所以应用程序类中使用:AfxMessageBox // 初始化 OLE 库 if (!AfxOleInit()) ...

  7. js实现OSS上传图片,STS临时授权访问OSS

    1. 引入aliyun-oss-sdk.min.js <script type="text/javascript" src="/static/js/common/a ...

  8. CDialog::DoModal()问题和_WIN32_WINNT

    1.从CDialogEx派生自己的CMyDialog,到DoModal()时总提示 error C2039: "DoModal": 不是"CMyDialog"的 ...

  9. 提交本地文件至gitlab已有的项目中(更新gitlab)

    gitlab代码更新 gitlab官网 1.安装git git官网 官网下载安装,安装过程一直next即可(路径自己选) 2.clone至本机 格式:git clone url(可转到指定目录克隆) ...

  10. Oracle中根据列名找到所属的表

    oracle中如何根据一个字段名查找出所属的表名? 用如下语句, select * from user_tab_columns where column_name='列名', 例子:select * ...