Python 梯度下降算法实现与可视化:一元函数求最小值
以下是一元函数的梯度下降代码和画图示例,使用 Python 语言实现:
import numpy as np
import matplotlib.pyplot as plt
# 定义一元函数 y = x^2 + 2x + 1
def func(x):
return np.power(x, 2) + 2 * x + 1
# 定义一元函数的导数
def dfunc(x):
return 2 * x + 2
# 梯度下降算法
def gradient_descent(x_start, df, epochs, lr):
'''
x_start: x 的初始值
df: y 的导函数
epochs: 迭代次数
lr: 学习率
'''
xs = np.zeros(epochs+1)
xs[0] = x_start
for i in range(epochs):
xs[i+1] = xs[i] - lr * df(xs[i])
return xs
# 运行梯度下降算法
x_start = -5
epochs = 50
lr = 0.1
x = gradient_descent(x_start, dfunc, epochs, lr)
# 画出函数曲线和梯度下降过程
plt.plot(np.linspace(-5, 3, 100), func(np.linspace(-5, 3, 100)), label='function')
plt.plot(x, func(x), 'r', label='gradient descent')
plt.legend()
plt.show()
运行结果:

在图中,蓝色曲线表示函数 'y=x^2+2x+1',红色点表示梯度下降过程中的迭代点。可以看出,随着迭代次数的增加,梯度下降算法越来越接近函数的最小值点 'x=-1',最终收敛到了此点。
原文地址: https://www.cveoy.top/t/topic/mYDI 著作权归作者所有。请勿转载和采集!