通过梯度下降找最小函数值

import random


def fun(x):
    return x ** 2 + 3 * x + 5


def derivative(x):
    return 2 * x + 3


if __name__ == '__main__':
    x = random.randint(0, 50)
    learn_rate = 0.01
    while True:
        temp_value = derivative(x)
        if abs(temp_value) < 0.000001:
            break

        if temp_value > 0:
            change_value = -temp_value * learn_rate
        else:
            change_value = temp_value * learn_rate
        x += change_value
        print(f'x:{x},min_value:{fun(x)}')

你可能感兴趣的:(通过梯度下降找最小函数值)