Yoggy机器学习-用python实现梯度下降算法

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()

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值