Matplotlib绘制简单函数的梯度下降法
➤01 一维函数
使用matplotlib的绘制函数是非常方便和容易的。
下面这个有趣的例子来自于飞浆PaddlePaddle深度学习实战P20中的例子。
1.简单的例子
演示了对于y=x2y = x^2y=x2函数通过局部的梯度下降方法来逐步获得全局极小值。
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# DEMO1.PY -- by Dr. ZhuoQing 2020-11-16
#
# Note:
#============================================================from headm import *#------------------------------------------------------------
def func(x):return square(x)def dfunc(x):return 2 * x # Derivative of x**2#------------------------------------------------------------
def gradient_descent(x_start, func_deri, epochs, learning_rate):theta_x = zeros(epochs+1)temp_x = x_starttheta_x[0] = temp_xfor i in range(epochs):deri_x = func_deri(temp_x)delta = -deri_x * learning_ratetemp_x = temp_x + deltatheta_x[i+1] = temp_xreturn theta_x#------------------------------------------------------------
def mat_plot():line_x = linspace(-5, 5, 100)line_y = func(line_x)x_start = -5epochs = 5lr = 0.3x = gradient_descent(x_start, dfunc, epochs, lr)color = 'r'plt.plot(line_x, line_y, c='b')plt.plot(x, func(x), c=color, linestyle='--', linewidth=1, label='lr={}'.format(lr))plt.scatter(x, func(x), color=color)plt.xlabel('x')plt.ylabel('x^2')plt.legend()plt.show()mat_plot()#------------------------------------------------------------
# END OF FILE : DEMO1.PY
#============================================================
▲ 绘制x**2梯度下降
2.绘制不同Learning Rate的梯度下降过程
绘制不同Learning Rate下的梯度下降方法对应的迭代过程。
▲ 学习速率从0.01增加到1.5
def mat_plot(learning_rate=0.3):line_x = linspace(-5, 5, 100)line_y = func(line_x)x_start = -5epochs = 10lr = learning_ratex = gradient_descent(x_start, dfunc, epochs, lr)color = 'r'plt.clf()plt.plot(line_x, line_y, c='b')plt.plot(x, func(x), c=color, linestyle='--', linewidth=1, label='lr=%4.2f'%lr)plt.scatter(x, func(x), color=color)plt.xlabel('x')plt.ylabel('x^2')plt.legend(loc='upper right')
# plt.show()plt.draw()plt.pause(.001)#------------------------------------------------------------
pltgif = PlotGIF()for lr in linspace(0.01, 1.5, 100):mat_plot(lr)if lr > 0.01:pltgif.append(plt)pltgif.save(r'd:\temp\1.gif')
➤02 二维函数
根据 Python 中的3Dplot 中给出的轮廓函数,来进行梯度下降的实验。
1.函数
Z(x,y)=e−(x+1)2−(y+0.5)2−e−(x−1)2−(y−0.5)2Z\left( {x,y} \right) = e^{ - \left( {x + 1} \right)^2 - \left( {y + 0.5} \right)^2 } - e^{ - \left( {x - 1} \right)^2 - \left( {y - 0.5} \right)^2 }Z(x,y)=e−(x+1)2−(y+0.5)2−e−(x−1)2−(y−0.5)2
▲ 二维函数的等高线图
def func(x,y):res = exp(-(x+1)**2-(y+0.5)**2)-exp(-(x-1)**2-(y-0.5)**2)return res*2def dfunc(x,y):dx = -2*(x+1)*exp(-(x+1)**2-(y+0.5)**2) + 2*(x-1)*exp(-(x-1)**2-(y-0.5)**2)dy = -2*(y+0.5)*exp(-(x+1)**2-(y+0.5)**2) + 2*(y-0.5)*exp(-(x-1)**2-(y-0.5)**2)return dx*2,dy*2def gradient_descent(x_start, y_start, epochs, learning_rate):theta_x = []theta_y = []temp_x = x_starttemp_y = y_starttheta_x.append(temp_x)theta_y.append(temp_y)for i in range(epochs):dx,dy = dfunc(temp_x, temp_y)temp_x = temp_x - dx*learning_ratetemp_y = temp_y - dy*learning_ratetheta_x.append(temp_x)theta_y.append(temp_y)return theta_x, theta_y#------------------------------------------------------------
def mat_plot(learning_rate=0.3):delta = 0.025x = arange(-3.0, 3.0, delta)y = arange(-3.0, 3.0, delta)X,Y = meshgrid(x,y)Z = func(X, Y)CS = plt.contour(X, Y, Z)plt.clabel(CS, inline=0.5, fontsize=6)plt.xlabel('x')plt.ylabel('y')plt.grid(True)plt.axis([-3, 3, -2, 2])plt.tight_layout()plt.show()
函数Z(x,y)对x,y求偏导数:
∂Z∂x=(−2x−2)e−(x+1)2−(y+0.5)2−(−2x+2)e−(x−1)2−(y−0.5)2{{\partial Z} \over {\partial x}} = \left( { - 2x - 2} \right)e^{ - \left( {x + 1} \right)^2 - \left( {y + 0.5} \right)^2 } - \left( { - 2x + 2} \right)e^{ - \left( {x - 1} \right)^2 - \left( {y - 0.5} \right)^2 }∂x∂Z=(−2x−2)e−(x+1)2−(y+0.5)2−(−2x+2)e−(x−1)2−(y−0.5)2
∂Z∂y=(−2y−1.0)e−(x+1)2−(y+0.5)2−(−2y+1.0)e−(x−1)2−(y−0.5)2{{\partial Z} \over {\partial y}} = \left( { - 2y - 1.0} \right)e^{ - \left( {x + 1} \right)^2 - \left( {y + 0.5} \right)^2 } - \left( { - 2y + 1.0} \right)e^{ - \left( {x - 1} \right)^2 - \left( {y - 0.5} \right)^2 }∂y∂Z=(−2y−1.0)e−(x+1)2−(y+0.5)2−(−2y+1.0)e−(x−1)2−(y−0.5)2
from sympy import symbols,simplify,expand,print_latex
from sympy import diff,exp#------------------------------------------------------------
x,y,f = symbols('x,y,f')f=exp(-(x+1)**2-(y+0.5)**2)-exp(-(x-1)**2-(y-0.5)**2)dfdx = diff(f,x)
dfdy = diff(f,y)result = dfdy#------------------------------------------------------------
print_latex(result)
tspexecutepythoncmd("msg2latex")
clipboard.copy(str(result))
2.二维梯度下降
▲ 梯度下降的迭代路线
如下是在Learning-Rate=0.1, Epochs在1 ~ 21的变化的动图。
如下是:Epochs=20,Learning-Rate从0.01到1.2之间变化。
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# TEST3.PY -- by Dr. ZhuoQing 2020-11-16
#
# Note:
#============================================================from headm import *def func(x,y):res = exp(-(x+1)**2-(y+0.5)**2)-exp(-(x-1)**2-(y-0.5)**2)return res*2def dfunc(x,y):dx = -2*(x+1)*exp(-(x+1)**2-(y+0.5)**2) + 2*(x-1)*exp(-(x-1)**2-(y-0.5)**2)dy = -2*(y+0.5)*exp(-(x+1)**2-(y+0.5)**2) + 2*(y-0.5)*exp(-(x-1)**2-(y-0.5)**2)return dx*2,dy*2def gradient_descent(x_start, y_start, epochs, learning_rate):theta_x = []theta_y = []temp_x = x_starttemp_y = y_starttheta_x.append(temp_x)theta_y.append(temp_y)for i in range(epochs):dx,dy = dfunc(temp_x, temp_y)temp_x = temp_x - dx*learning_ratetemp_y = temp_y - dy*learning_ratetheta_x.append(temp_x)theta_y.append(temp_y)return theta_x, theta_y#------------------------------------------------------------
def mat_plot(epochs=10, learning_rate=0.3):lr = learning_ratedelta = 0.025x = arange(-3.0, 3.0, delta)y = arange(-3.0, 3.0, delta)X,Y = meshgrid(x,y)Z = func(X, Y)dx,dy = gradient_descent(-0.9, -0.25, epochs, lr)plt.clf()plt.scatter(dx, dy, color='r')plt.plot(dx, dy, linewidth=1, linestyle='--', label='lr=%4.2f'%lr)CS = plt.contour(X, Y, Z)plt.clabel(CS, inline=0.5, fontsize=6)plt.xlabel('x')plt.ylabel('y')plt.grid(True)plt.axis([-3, 3, -2, 2])plt.tight_layout()plt.legend(loc='upper right')plt.draw()plt.pause(.001)#------------------------------------------------------------pltgif = PlotGIF()for i in linspace(0.01, 1.2, 50):mat_plot(10, i)if i > 0.01:pltgif.append(plt)pltgif.save(r'd:\temp\1.gif')#------------------------------------------------------------
# END OF FILE : TEST3.PY
#============================================================
#------------------------------------------------------------
def mat_plot(epochs=10, learning_rate=0.3):lr = learning_ratedelta = 0.025x = arange(-3.0, 3.0, delta)y = arange(-3.0, 3.0, delta)X,Y = meshgrid(x,y)Z = func(X, Y)dx,dy = gradient_descent(-0.9, -0.25, epochs, lr)plt.clf()ax = plt.axes(projection='3d')
# ax.plot_surface(X,Y,Z, cmap='coolwarm')ax.contour(X,Y,Z)ax.scatter(dx, dy, func(array(dx),array(dy)), color='r')ax.plot(dx, dy, func(array(dx), array(dy)), linewidth=1, linestyle='--', label='lr=%4.2f'%lr)# CS = plt.contour(X, Y, Z)
# plt.clabel(CS, inline=0.5, fontsize=6)plt.xlabel('x')plt.ylabel('y')plt.grid(True)plt.axis([-3, 3, -2, 2])plt.tight_layout()plt.legend(loc='upper right')plt.draw()plt.pause(.1)#------------------------------------------------------------pltgif = PlotGIF()for i in linspace(0.01, 1.2, 100):mat_plot(20, i)if i > 0.01:pltgif.append(plt)pltgif.save(r'd:\temp\1.gif')#------------------------------------------------------------
# END OF FILE : TEST3.PY
#============================================================
Matplotlib绘制简单函数的梯度下降法相关推荐
- 通俗易懂讲解梯度下降法!
Datawhale干货 作者:知乎King James,伦敦国王大学 知乎 | https://zhuanlan.zhihu.com/p/335191534 前言:入门机器学习必须了解梯度下降法,虽然 ...
- Python 梯度下降法
题目描述: 自定义一个可微并且存在最小值的一元函数,用梯度下降法求其最小值.并绘制出学习率从0.1到0.9(步长0.1)时,达到最小值时所迭代的次数的关系曲线,根据该曲线给出简单的分析. 代码: # ...
- 利用梯度下降法求解一元线性回归和多元线性回归
文章目录 原理以及公式 [1]一元线性回归问题 [2]多元线性回归问题 [3]学习率 [4]流程分析(一元线性回归) [5]流程分析(多元线性回归) 归一化原理以及每种归一化适用的场合 一元线性回归代 ...
- 吴恩达《机器学习》学习笔记四——单变量线性回归(梯度下降法)代码
吴恩达<机器学习>学习笔记四--单变量线性回归(梯度下降法)代码 一.问题介绍 二.解决过程及代码讲解 三.函数解释 1. pandas.read_csv()函数 2. DataFrame ...
- 基于随机梯度下降法的手写数字识别、epoch是什么、python实现
基于随机梯度下降法的手写数字识别.epoch是什么.python实现 一.普通的随机梯度下降法的手写数字识别 1.1 学习流程 1.2 二层神经网络类 1.3 使用MNIST数据集进行学习 注:关于什 ...
- 50行代码,带你理解梯度下降法(Gradient Descent Method)
梯度下降法是一种常见的优化算法,在机器学习中应用很广泛.本文从代码的角度,带你理解梯度下降法. 优化算法 优化指的是改变x以最小化或最大化某个函数 f(x) 的任务.通常以最小化 f(x) 指代大多数 ...
- Python机器学习:梯度下降法002模拟实现梯度下降法
模拟实现梯度下降法 import numpy as np import matplotlib.pyplot as plt 生成数据 plot_x = np.linspace(-1,6,141) pri ...
- 人工智能必备数学知识· 学习笔记 ·001【线性回归,最小二乘法梯度下降法】
注:笔记 来自课程 人工智能必备数学知识 Tips①:只是记录从这个课程学到的东西,不是推广.没有安利 Tips②:本笔记主要目的是为了方便自己遗忘查阅,或过于冗长.或有所缺省.或杂乱无章,见谅 Ti ...
- python机器学习库sklearn——SGD梯度下降法
分享一个朋友的人工智能教程.零基础!通俗易懂!风趣幽默!还带黄段子!大家可以看看是否对自己有帮助:点击打开 docker/kubernetes入门视频教程 全栈工程师开发手册 (作者:栾鹏) pyth ...
最新文章
- DVWA默认用户名密码
- pytroch一机多卡训练
- Java的异常:Error与Exception
- Hibernate从零开始_07_多对多关系(中间表)
- 二叉树前序、中序、后序遍历求法
- linux ba 模拟,在你的 Python 游戏中模拟引力 | Linux 中国
- Mysql的数据库和客户端环境搭建(三)
- 9.6.1 三维数据可视化之曲面图
- python 抓取搜狗微信出现的问题,求大神解决
- Google与GitHub 结盟,为保护软件供应链而战
- 起动缓慢_世界最大柴油机为何是压缩空气起动?那么它到底是如何起动的呢?...
- 内大考研计算机专业课,2019计算机考研专业课核心考点梳理
- linux中安装mysql5.1.73_linux安装mysql(5.1.73)
- 网上书店动态网页设计
- android局域网连接TSC桌面打印机打印
- Bluecoat Web无法正常显示页面解决方案
- php setfield什么意思,thinkphp教程专题
- 大学生程序设计邀请赛(华东师范大学)A
- win10 以太网消失了
- JSP中把动态页面转换为静态页面