梯度下降过程可视化
创作时间:
作者:
@小白创作中心
梯度下降过程可视化
引用
CSDN
1.
https://blog.csdn.net/weixin_43589323/article/details/137237632
梯度下降是机器学习和深度学习中的基础优化算法,其收敛过程受到学习率和初始位置的影响。本文通过自定义函数实现梯度下降过程的可视化,并通过多个示例展示了不同学习率和初始位置对收敛过程的影响。
可视化f(x) = x^2
学习率η = 0.1,较慢的收敛
学习率η = 0.5,比较好的收敛
学习率η = 0.9,振荡的收敛
可视化f(x) = 0.15πcos(0.15πx)
学习率η = 0.1,起始位置为15,收敛到一个极小值
学习率η = 0.2,起始位置为-8,收敛到一个极小值
学习率η = 3,起始位置为15,振荡收敛到圆点附近
总结
目标函数的最小化过程受到起始值和学习率(迭代步长)的影响,为了能够让收敛过程更加快速准确,需要认真对待初始化过程。
下面是绘图的源码
import torch
from torch import Tensor
from typing import Callable
import matplotlib.pyplot as plt
from matplotlib_inline import backend_inline
def use_svg_display():
"""Use the svg format to display a plot in Jupyter."""
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(4.5, 3.5)):
"""Set the figure size for matplotlib."""
use_svg_display()
plt.rcParams['figure.figsize'] = figsize
class GradientDesenctVisualization(object):
def __init__(self, func: Callable,
steps: int=10,
eta: float=0.1,
init_point: Tensor=None):
"""visualize gradient descent progress
Args:
func (Callable): objective function
steps (int, optional): total steps to perform gradient descent. Defaults to 10.
eta (float, optional): learing rate. Defaults to 0.1.
init_point (Tensor, optional) start point of the progress. Defaults to None.
"""
self.func = func
self.steps = steps
self.eta = eta
self.init_point = init_point
if self.init_point is None: # if not given, initialize with normal distribution
self.init_point = torch.randn(1, requires_grad=True)
assert self.init_point.requires_grad is True
def evoluation(self):
"""perform gradient descent progress
"""
x = self.init_point
eta = self.eta
func = self.func
steps = self.steps
# record evoluation of x
x_evoluation = [x.data.item()]
for _ in range(steps):
y = func(x) # compute output
y.backward() # backward
x.data -= eta * x.grad.data # compute next point
x.grad.data.zero_() # clear grad
x_evoluation.append(x.data.item()) # record evoluation
self.x_evoluation = x_evoluation
def show_trace(self, bound: float=None):
"""plot gradient descent progress
"""
x_evoluation = self.x_evoluation
f = self.func
# get bound of x_evoluation
if bound is None:
bound = max(abs(min(x_evoluation)), abs(max(x_evoluation)))
f_line = torch.arange(-bound, bound, 0.01)
set_figsize()
# plot graph of objective funciton
plt.plot(f_line, [f(x) for x in f_line], '-', c='b')
# plot the gradient descent progress
points = list(zip(x_evoluation, [f(x) for x in x_evoluation]))
# use annotate to plot the arrow
for i in range(len(points) - 1):
plt.gca().annotate("", xy=points[i+1], xytext=points[i],
arrowprops=dict(arrowstyle="->", lw=1.0, fc="red", ec="red"))
# plot the start position of the gradinet descent progress
ax1 = plt.plot(points[0][0], points[0][1], 'ro')
# plot the final position of the gradinet descent progress
ax2 = plt.plot(points[-1][0], points[-1][1], 'go')
plt.legend([ax1[0], ax2[0]], ['start', 'end'])
plt.title(f'$\eta$ = {self.eta:.3f}')
plt.xlim(-bound, bound)
plt.xlabel('x')
plt.ylabel('func')
plt.grid()
plt.show()
使用方法
import torch
c = torch.tensor(0.15 * torch.pi)
def func(x): # 目标函数
return x * torch.cos(c * x)
steps = 10 # 迭代次数
eta = 0.2 # 学习率
init_point = torch.tensor([-8.0], requires_grad=True) # 初始位置
# 初始化
gdv= GradientDesenctVisualization(func, steps, eta, init_point)
# 进行计算
gdv.evoluation()
# 可视化过程
gdv.show_trace()
热门推荐
临沂社保卡办理全攻略:从申请到使用一文通
冬日慕田峪:三条交通方式,西线雪景最佳
夯土加石砌,秦长城的古老建筑智慧
湿厕纸:清洁效果好还能直接冲,使用需适量
卫生纸冲马桶还是扔垃圾桶?这份指南请收好
55%民众仍选择丢垃圾桶,卫生纸冲厕到底行不行
新春将至话蛇年:传统吉祥话的现代演绎
爱的摇篮不摇晃,科学育儿有保障
2024年龙宝宝取什么名字好,龙年最旺男孩名字大全
一文读懂房屋面积:测量方法与分类标准详解
购房者注意:拿不到房产证的五大常见原因及处理办法
房屋面积测量指南:4步法确保交易公平与合规
《金刚经》第十品:内心的革命,从“不住相布施”开始
燃灯佛加持,《金刚经》第十品的奥秘
《金刚经》与抑郁症:心灵解脱的新途径?
莽山:南岭深处的生态明珠,世界级动植物宝库
从猴王寨到五指峰:湖南莽山冬季旅游全攻略
三天玩转莽山:猴王寨、天台山、温泉酒店全攻略
越南企业引入6S管理:六大措施打造高效办公环境
6S管理助力企业提升:六大要素与实施步骤详解
6S管理咨询助力企业高效缩减作业周期
年终资金流动频繁,五类洗钱手法需谨防
从百亿市场到百公里传输,中国量子通信领跑全球
离婚后如何重建财务?七大步骤助你重获经济独立
离婚诉讼权益保护与债务处理:福建地区法律指南
女性离婚权益保护:财产分割与子女抚养指南
精益管理跨领域实践:四大行业实现效率与质量双提升
枣泉发电化学试验班:7S管理全覆盖,培育特色班组文化
重要 vs 紧急:四象限法则教你科学管理时间
清蒸红烧到酸菜鱼:七种家常鱼肉烹饪法详解