梯度下降法求函数最小值(python,numpy)

#用梯度下降法求函数最小值
# coding: utf-8
import numpy as np
import matplotlib.pylab as plt
def _numerical_gradient_no_batch(f, x):  #求函数的梯度值
    h = 1e-4  # 0.0001
    grad = np.zeros_like(x)
    for idx in range(x.size):
        tmp_val = x[idx]
        x[idx] = float(tmp_val) + h
        fxh1 = f(x)  # f(x+h)
        x[idx] = tmp_val - h
        fxh2 = f(x)  # f(x-h)
        grad[idx] = (fxh1 - fxh2) / (2 * h)
        x[idx] = tmp_val  # 还原值
    return grad

def gradient_descent(f, init_x, lr=0.01, step_num=100):   #梯度下降法
    x = init_x            #初始化
    x_history = []        #记录寻优过程中的值

    for i in range(step_num):
        x_history.append( x.copy() )

        grad = _numerical_gradient_no_batch(f, x)   #计算函数梯度
        x -= lr * grad              #沿着梯度方向下降,空学习率控制每次下降的多少

    return x, np.array(x_history)


def function_2(x):
    return x[0]**2 + x[1]**2         #函数f(x)=x0^2+x1^2

init_x = np.array([-3.0, 4.0])        #从(-3,4)开始搜索

lr = 0.1        #学习率为0.1
step_num = 20    #共搜索20步
x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)  #梯度下降法
#输出结果
print(x)   #结果很接近最小值(0,0)
#画出历史值
plt.plot( [-5, 5], [0,0], '--b')
plt.plot( [0,0], [-5, 5], '--b')
plt.plot(x_history[:,0], x_history[:,1], 'o')
plt.xlim(-3.5, 3.5)
plt.ylim(-4.5, 4.5)
plt.xlabel("X0")
plt.ylabel("X1")
plt.show()

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值