【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梯度下降:拉格乘子法

相关内容

热门资讯

智慧吴江app安卓系统,安卓系... 你知道吗?最近吴江地区掀起了一股智慧风潮,一款名为“智慧吴江app”的应用在安卓系统上大受欢迎。这款...
苹果系统听歌app安卓,跨平台... 你有没有发现,无论是走在街头还是坐在家里,音乐总是能瞬间点燃我们的心情?而在这个音乐无处不在的时代,...
安卓系统卡顿根源,性能瓶颈与优... 手机用久了是不是感觉越来越卡?是不是每次打开应用都要等半天,甚至有时候直接卡死?别急,今天就来跟你聊...
电脑系统怎么装安卓系统,电脑系... 你有没有想过,把安卓系统装在你的电脑上,是不是就像给电脑穿上了时尚的新衣呢?想象你可以在电脑上直接使...
安卓系统华为手环app,健康管... 你有没有发现,现在的生活越来越离不开智能设备了?手机、平板、手表……这些小玩意儿不仅让我们的生活变得...
switch lite刷安卓系... 你有没有想过,你的Switch Lite除了玩那些可爱的任天堂游戏,还能干些什么呢?没错,今天我要给...
想买华为但是安卓系统,尽享安卓... 最近是不是也被华为的新款手机给迷住了?看着那流畅的线条和强大的性能,是不是心动了呢?但是,一想到安卓...
怎么拷安卓系统文件,安卓系统文... 你有没有想过,手机里的那些安卓系统文件,其实就像是一扇通往手机世界的秘密通道呢?想要深入了解你的安卓...
安卓系统移植按键失灵,安卓系统... 最近你的安卓手机是不是也遇到了按键失灵的尴尬情况呢?这可真是让人头疼啊!别急,今天就来给你详细解析一...
安卓系统更新管理在哪,全面解析... 你有没有发现,你的安卓手机最近是不是总在提醒你更新系统呢?别急,别急,今天就来手把手教你,安卓系统更...
安卓系统哪里出的,从诞生地到全... 你有没有想过,我们每天离不开的安卓系统,它究竟是从哪里冒出来的呢?是不是觉得这个问题有点儿像是在问星...
最好的电脑安卓系统,最佳电脑安... 亲爱的电脑迷们,你是否在寻找一款既能满足你工作需求,又能让你畅享娱乐的电脑操作系统呢?今天,我要给你...
安卓系统保密性,守护隐私的坚实... 你知道吗?在这个信息爆炸的时代,保护个人隐私变得比以往任何时候都重要。尤其是对于安卓系统用户来说,了...
苹果系统下载安卓版本,安卓版本... 你有没有想过,为什么苹果系统的手机那么受欢迎,却还有人想要下载安卓版本呢?这背后可是有着不少故事呢!...
安卓系统如何下载carplay... 你是不是也和我一样,对安卓系统上的CarPlay功能充满了好奇?想象在安卓手机上就能享受到苹果Car...
退回安卓系统的理由,揭秘安卓系... 你有没有想过,为什么有些人会选择退回到安卓系统呢?这可不是一件简单的事情,背后可是有着不少原因哦!让...
安卓机系统互通吗,共创智能生态 你有没有想过,你的安卓手机里的应用和电脑上的安卓应用是不是可以无缝对接呢?是不是有时候觉得手机上的某...
安卓源码 添加系统应用,系统应... 你有没有想过,手机里的那些系统应用是怎么来的?是不是觉得它们就像天外来物,神秘又神奇?其实,只要你愿...
安卓系统能否播放flv,全面解... 你有没有想过,你的安卓手机里那些珍贵的FLV视频文件,到底能不能顺利播放呢?这可是个让人挠头的问题,...
奔驰c系安卓系统,智能驾驶体验... 你有没有发现,最近开奔驰C系的小伙伴们都在悄悄地谈论一个新玩意儿——安卓系统!没错,就是那个我们手机...