import numpy as np
import matplotlib.pyplot as plt
# 定义目标函数和其梯度
def f(x):
return (x - 3)**2
def grad_f(x):
return 2 * (x - 3)
# 梯度下降算法
def gradient_descent(starting_point, learning_rate, num_iterations):
x = starting_point
x_values = [x]
for _ in range(num_iterations):
x = x - learning_rate * grad_f(x)
x_values.append(x)
return x, x_values
# 初始化参数
starting_point = 0.0
learning_rate = 0.1
num_iterations = 20
# 运行梯度下降算法
final_x, x_values = gradient_descent(starting_point, learning_rate, num_iterations)
# 打印最终结果
print("最终的x值:", final_x)
# 生成图像
x_range = np.linspace(-2, 8, 400)
y_range = f(x_range)
plt.figure(figsize=(10, 6))
plt.plot(x_range, y_range, label='f(x) = (x - 3)^2')
plt.scatter(x_values, f(np.array(x_values)), color='red', label='梯度下降过程')
for i, (x, y) in enumerate(zip(x_values, f(np.array(x_values)))):
plt.text(x, y, f'{i}', fontsize=8, verticalalignment='bottom')
plt.title('梯度下降优化过程')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()
Yoggy机器学习-用python实现梯度下降算法
最新推荐文章于 2024-08-01 16:10:25 发布