【ML-SVM案例学习】002梯度下降之求解最优解
admin
2024-01-29 09:20:24
0

文章目录

  • 前言
  • 一、代码程序
    • 1.引入库
    • 2.一维原始图像与导函数
    • 3.使用梯度下降法求解
    • 4.构建数据与画图
    • 5.二维原始图像与导函数
    • 6. 使用梯度下降法求解
    • 7.构建数据与绘图
  • 二、完整代码
  • 总结


前言

【ML-SVM案例】会有十种SVM案例,供大家用来学习。本文只是实现梯度下降,求解最优解。后面一章将会实现003梯度下降:拉格乘子法


提示:以下是本篇文章正文内容,下面案例可供参考

一、代码程序

1.引入库

代码如下(示例):

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D

2.一维原始图像与导函数

代码如下(示例):

# 解决中文显示问题
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False"""一维原始图像"""
def f1(x):return 0.5 * (x - 0.25) ** 2
# 导函数
def h1(x):return 0.5 * 2 * (x - 0.25)

3.使用梯度下降法求解

GD_X = []
GD_Y = []
x = 4
alpha = 0.5
f_change = f1(x)
f_current = f_change
GD_X.append(x)
GD_Y.append(f_current)
iter_num = 0
while f_change > 1e-10 and iter_num < 100:iter_num += 1x = x - alpha * h1(x)tmp = f1(x)f_change = np.abs(f_current - tmp)f_current  = tmpGD_X.append(x)GD_Y.append(f_current)
print(u"最终结果为:(%.5f, %.5f)" % (x, f_current))
print(u"迭代过程中X的取值,迭代次数:%d" % iter_num)
print(GD_X)

4.构建数据与画图

X = np.arange(-4, 4.5, 0.05)
Y = np.array(list(map(lambda t: f1(t), X)))plt.figure(facecolor='w')
plt.plot(X, Y, 'r-', linewidth=2)
plt.plot(GD_X, GD_Y, 'ko--', linewidth=2)
plt.title(u'函数$y=0.5 * (θ - 0.25)^2$; \n学习率:%.3f; 最终解:(%.3f, %.3f);迭代次数:%d' % (alpha, x, f_current, iter_num))
plt.show()

5.二维原始图像与导函数

"""二维原始图像"""
def f2(x, y):return 0.6 * (x + y) ** 2 - x * y
# 导函数
def hx2(x, y):return 0.6 * 2 * (x + y) - y
def hy2(x, y):return 0.6 * 2 * (x + y) - x

6. 使用梯度下降法求解

GD_X1 = []
GD_X2 = []
GD_Y = []
x1 = 4
x2 = 4
alpha = 0.5
f_change = f2(x1, x2)
f_current = f_change
GD_X1.append(x1)
GD_X2.append(x2)
GD_Y.append(f_current)
iter_num = 0
while f_change > 1e-10 and iter_num < 100:iter_num += 1prex1 = x1prex2 = x2x1 = x1 - alpha * hx2(prex1, prex2)x2 = x2 - alpha * hy2(prex1, prex2)tmp = f2(x1, x2)f_change = np.abs(f_current - tmp)f_current  = tmpGD_X1.append(x1)GD_X2.append(x2)GD_Y.append(f_current)
print(u"最终结果为:(%.5f, %.5f, %.5f)" % (x1, x2, f_current))
print(u"迭代过程中X的取值,迭代次数:%d" % iter_num)
print(GD_X1)

7.构建数据与绘图

# 构建数据
X1 = np.arange(-4, 4.5, 0.2)
X2 = np.arange(-4, 4.5, 0.2)
X1, X2 = np.meshgrid(X1, X2)
Y = np.array(list(map(lambda t: f2(t[0], t[1]), zip(X1.flatten(), X2.flatten()))))
Y.shape = X1.shape# 画图
fig = plt.figure(facecolor='w')
ax = Axes3D(fig)
ax.plot_surface(X1, X2, Y, rstride=1, cstride=1, cmap=plt.cm.jet)
ax.plot(GD_X1, GD_X2, GD_Y, 'ko--')ax.set_title(u'函数$y=0.6 * (θ1 + θ2)^2 - θ1 * θ2$;\n学习率:%.3f; 最终解:(%.3f, %.3f, %.3f);迭代次数:%d' % (alpha, x1, x2, f_current, iter_num))
plt.show()

二、完整代码

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D# 解决中文显示问题
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False"""一维原始图像"""
def f1(x):return 0.5 * (x - 0.25) ** 2
# 导函数
def h1(x):return 0.5 * 2 * (x - 0.25)# 使用梯度下降法求解
GD_X = []
GD_Y = []
x = 4
alpha = 0.5
f_change = f1(x)
f_current = f_change
GD_X.append(x)
GD_Y.append(f_current)
iter_num = 0
while f_change > 1e-10 and iter_num < 100:iter_num += 1x = x - alpha * h1(x)tmp = f1(x)f_change = np.abs(f_current - tmp)f_current  = tmpGD_X.append(x)GD_Y.append(f_current)
print(u"最终结果为:(%.5f, %.5f)" % (x, f_current))
print(u"迭代过程中X的取值,迭代次数:%d" % iter_num)
print(GD_X)# 构建数据
X = np.arange(-4, 4.5, 0.05)
Y = np.array(list(map(lambda t: f1(t), X)))# 画图
plt.figure(facecolor='w')
plt.plot(X, Y, 'r-', linewidth=2)
plt.plot(GD_X, GD_Y, 'ko--', linewidth=2)
plt.title(u'函数$y=0.5 * (θ - 0.25)^2$; \n学习率:%.3f; 最终解:(%.3f, %.3f);迭代次数:%d' % (alpha, x, f_current, iter_num))
plt.show()"""二维原始图像"""
def f2(x, y):return 0.6 * (x + y) ** 2 - x * y
# 导函数
def hx2(x, y):return 0.6 * 2 * (x + y) - y
def hy2(x, y):return 0.6 * 2 * (x + y) - x# 使用梯度下降法求解
GD_X1 = []
GD_X2 = []
GD_Y = []
x1 = 4
x2 = 4
alpha = 0.5
f_change = f2(x1, x2)
f_current = f_change
GD_X1.append(x1)
GD_X2.append(x2)
GD_Y.append(f_current)
iter_num = 0
while f_change > 1e-10 and iter_num < 100:iter_num += 1prex1 = x1prex2 = x2x1 = x1 - alpha * hx2(prex1, prex2)x2 = x2 - alpha * hy2(prex1, prex2)tmp = f2(x1, x2)f_change = np.abs(f_current - tmp)f_current  = tmpGD_X1.append(x1)GD_X2.append(x2)GD_Y.append(f_current)
print(u"最终结果为:(%.5f, %.5f, %.5f)" % (x1, x2, f_current))
print(u"迭代过程中X的取值,迭代次数:%d" % iter_num)
print(GD_X1)# 构建数据
X1 = np.arange(-4, 4.5, 0.2)
X2 = np.arange(-4, 4.5, 0.2)
X1, X2 = np.meshgrid(X1, X2)
Y = np.array(list(map(lambda t: f2(t[0], t[1]), zip(X1.flatten(), X2.flatten()))))
Y.shape = X1.shape# 画图
fig = plt.figure(facecolor='w')
ax = Axes3D(fig)
ax.plot_surface(X1, X2, Y, rstride=1, cstride=1, cmap=plt.cm.jet)
ax.plot(GD_X1, GD_X2, GD_Y, 'ko--')ax.set_title(u'函数$y=0.6 * (θ1 + θ2)^2 - θ1 * θ2$;\n学习率:%.3f; 最终解:(%.3f, %.3f, %.3f);迭代次数:%d' % (alpha, x1, x2, f_current, iter_num))
plt.show()"""二维原始图像"""
def f2(x, y):return 0.15 * (x + 0.5) ** 2 + 0.25 * (y  - 0.25) ** 2 + 0.35 * (1.5 * x - 0.2 * y + 0.35 ) ** 2  
## 偏函数
def hx2(x, y):return 0.15 * 2 * (x + 0.5) + 0.25 * 2 * (1.5 * x - 0.2 * y + 0.35 ) * 1.5
def hy2(x, y):return 0.25 * 2 * (y  - 0.25) - 0.25 * 2 * (1.5 * x - 0.2 * y + 0.35 ) * 0.2# 使用梯度下降法求解
GD_X1 = []
GD_X2 = []
GD_Y = []
x1 = 4
x2 = 4
alpha = 0.5
f_change = f2(x1, x2)
f_current = f_change
GD_X1.append(x1)
GD_X2.append(x2)
GD_Y.append(f_current)
iter_num = 0
while f_change > 1e-10 and iter_num < 100:iter_num += 1prex1 = x1prex2 = x2x1 = x1 - alpha * hx2(prex1, prex2)x2 = x2 - alpha * hy2(prex1, prex2)tmp = f2(x1, x2)f_change = np.abs(f_current - tmp)f_current  = tmpGD_X1.append(x1)GD_X2.append(x2)GD_Y.append(f_current)
print(u"最终结果为:(%.5f, %.5f, %.5f)" % (x1, x2, f_current))
print(u"迭代过程中X的取值,迭代次数:%d" % iter_num)
print(GD_X1)# 构建数据
X1 = np.arange(-4, 4.5, 0.2)
X2 = np.arange(-4, 4.5, 0.2)
X1, X2 = np.meshgrid(X1, X2)
Y = np.array(list(map(lambda t: f2(t[0], t[1]), zip(X1.flatten(), X2.flatten()))))
Y.shape = X1.shape# 画图
fig = plt.figure(facecolor='w')
ax = Axes3D(fig)
ax.plot_surface(X1, X2, Y, rstride=1, cstride=1, cmap=plt.cm.jet)
ax.plot(GD_X1, GD_X2, GD_Y, 'ko--')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')ax.set_title(u'函数;\n学习率:%.3f; 最终解:(%.3f, %.3f, %.3f);迭代次数:%d' % (alpha, x1, x2, f_current, iter_num))
plt.show()

总结

001梯度下降:一维和二维图像
003梯度下降:拉格乘子法

相关内容

热门资讯

安卓和小米系统怎么换机,轻松实... 你有没有想过,手机用久了,是不是有点腻味了呢?想要换一台新手机,但是又不知道怎么从安卓系统切换到小米...
安卓最好的系统软件,揭秘最佳系... 你有没有想过,为什么你的安卓手机总是那么流畅,那么好玩?这背后,可离不开那些默默无闻的系统软件呢!今...
安卓系统屏幕如何截屏,安卓屏幕... 亲爱的手机控们,你是不是也经常想要截取手机屏幕上的精彩瞬间呢?别急,今天就来手把手教你如何轻松截屏,...
安卓系统为何总会卡顿,性能优化... 你有没有发现,不管你的安卓手机多新,用不了多久就会变得卡顿呢?这可真是让人头疼的问题。今天,我们就来...
手机适配高版本安卓系统,揭秘高... 你有没有发现,最近你的手机好像变得越来越不给力了?是不是觉得打开某个应用时总是卡顿,或者某些功能突然...
苹果和安卓系统原理,架构、差异... 你有没有想过,为什么你的手机里装了那么多应用,却还是觉得不够用?其实,这一切都离不开我们每天离不开的...
小米2s双系统安卓系统 你有没有想过,一部手机,竟然能同时拥有两个操作系统?没错,就是那种可以让你在安卓和另一个系统之间自由...
王者荣耀什么是安卓系统,畅享手... 亲爱的王者荣耀玩家们,你是否曾好奇过,这款火爆全网的手机游戏,究竟是如何在安卓系统上运行得如此流畅呢...
百度系统和安卓系统区别,差异解... 你有没有想过,为什么你的手机里装的是安卓系统,而朋友的手机却是百度系统呢?这两种系统各有千秋,今天就...
旧安卓刷鸿蒙系统教程,刷鸿蒙系... 亲爱的安卓用户们,你是否对鸿蒙系统心生向往,想要让你的旧安卓手机也体验一番全新的操作系统呢?别急,今...
原生安卓系统如何换字体,轻松实... 你有没有发现,手机上的字体有时候看久了,眼睛都累得不行?别急,今天就来教你怎么给原生安卓系统换个新字...
安卓系统按键切歌 你有没有遇到过在听歌的时候,突然想切换到下一首,却发现按键操作起来有点麻烦?别急,今天就来给你详细介...
安卓系统买哪款耳机 你最近是不是在为安卓系统的新耳机犯愁呢?市面上那么多品牌,那么多型号,真是让人挑花了眼。别急,今天我...
安卓导航系统无响应,排查与解决... 最近是不是你也遇到了安卓导航系统无响应的尴尬情况?别急,让我来给你详细剖析一下这个问题,让你从此告别...
安卓系统进不去微信,安卓系统无... 最近是不是你也遇到了这样的烦恼:安卓手机突然进不去微信了?别急,让我来给你详细说说这个问题的原因和解...
安卓2代系统升级,跨越时代的飞... 你有没有发现,你的安卓手机最近是不是变得有点儿慢吞吞的?别急,别急,这可能是你的安卓2代系统需要升级...
安卓主屏换成苹果系统,体验全新... 你知道吗?最近有个朋友突然告诉我,他打算把安卓手机的主屏换成苹果系统的界面。这可真是让人眼前一亮的主...
安卓系统编程岗位要求 你有没有想过,为什么安卓系统这么受欢迎?没错,就是因为它强大、灵活,而且开发起来超级有趣!那么,想要...
安卓手机哪个系统没广告,揭秘无... 你有没有发现,用安卓手机的时候,广告总是无处不在,让人有点头疼呢?今天,就让我来给你揭秘安卓手机中哪...
安卓没电系统提示音,唤醒你的紧... 手机没电了,是不是瞬间感觉整个人都不好了?尤其是安卓手机,那系统提示音一响,简直就像是在耳边嗡嗡嗡地...