【Python】梯度下降法求解一元二次函数的波谷

import random


'''
drd notes: 使用梯度下降法 求y=3x^2 + 7x - 10波谷时x的值
'''


def my_function(x):
    # drd notes:y = 3x^2 + 7x - 10
    return 3 * x * x + 7 * x - 10


def my_function_slop(x):
    # drd notes: 切线方程对应为y = 6x + 7
    return 6 * x + 7


# drd notes:求y最小值时的x
def gradient_descent_min():
    # drd notes: 产生随机初始化的点
    x0 = random.randint(-100, 100)
    w = 0.001
    precision = 1e-6
    count = 0
    # drd notes:一元二次方程经过多次 梯度下降 走法,最后必然会在最小值附近
    while True:
        x1 = x0 - my_function_slop(x0) * w
        count = count + 1
        # drd notes: 达到精度后就推出
        if abs(my_function(x1) - my_function(x0)) < precision:
            break
        x0 = x1

    # drd notes:波谷点为(-7/6, 169/12), -7/6 = -1.1666666
    # drd notes: 经过 1001 迭代后,当x = -1.161392224931042时,y有最小值-14.083249874126466
    # 经过 1472 迭代后,当x = -1.1719342628187626时,y有最小值-14.083250090625668
    print('经过 {} 迭代后,当x = {}时,y有最小值{}'.format(count, x0, my_function(x0)))


if __name__ == '__main__':
    gradient_descent_min()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值