下面是使用梯度下降法求解函数f(X)=sin(x)/x 的最小值的Python代码,代码包含函数定义、梯度下降算法、结果可视化等功能:

import numpy as np
import matplotlib.pyplot as plt

def f(X):
    return np.sin(X) / X

def f_prime(X):
    return (X * np.cos(X) - np.sin(X)) / X**2

def gradient_descent(X0, learning_rate):
    Val = []
    Func_Value = []

    print('Initial point is:', X0, '\n')
    X = X0
    f = f(X)
    print('The initial function value is:', f, '\n')
    Val.append(X)
    Func_Value.append(f)

    count = 0
    iter_max = 100
    Delta = 10

    while count < iter_max and Delta > 10**(-4):
        count += 1
        print('The current iteration is:', count, '\n')

        up_X = X - learning_rate * f_prime(X)
        up_f = f(up_X)
        Delta = np.abs(f - up_f)

        X = up_X
        f = up_f
        Val.append(X)
        Func_Value.append(f)

        print('The function value is:', f, '\n')
        print('The var is:', X, '\n')

    X_end = X
    first_grad = f_prime(X_end)
    second_grad = (- np.sin(X_end) / X_end - 2 * np.cos(X_end) / (X_end**2) + 2 * np.sin(X_end) / (X_end**3))

    print('It converges after', count, 'iterations, and the local minimal is', X_end, '\n')
    print('First gradient of the local minimal point is', first_grad, '\n')
    print('Second gradient of the local minimal point is', second_grad, '\n')

    return [Val, Func_Value, count]

if __name__=="__main__":
    x_min = -15
    x_max = 15
    sample_num = 1000
    dot_X = np.linspace(x_min, x_max, sample_num)
    dot_Y = f(dot_X)

    X0 = -5
    learning_rate = 1
    [Val, Func_Value, count] = gradient_descent(X0, learning_rate)
    Val = np.array(Val)
    Func_Value = np.array(Func_Value)

    np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
    print(Val)
    print(Func_Value)

    plt.figure()
    plt.plot(dot_X, dot_Y, "-", c='b')

    for i in range(count+1):
        plt.scatter(Val[i], Func_Value[i], color='r', s=40, marker='o')
        text_pt = plt.text(Val[i] + 0.1, Func_Value[i], '', fontsize=10)
        text_pt.set_text(r'$x_{%d}$' % i)
        plt.pause(0.2)

    plt.title(r'$\eta = %.3f$, $x_{0} = %.1f$, it iterates %d steps in total' % (learning_rate, X0, count), fontsize=10)
    plt.show()

通过运行上述代码,您将得到一个动态展示梯度下降过程的图像,并输出最终收敛结果以及局部极小值点的梯度信息。

代码功能解释:

  • 函数定义: f(X)f_prime(X) 分别定义了目标函数和其一阶导数,用于计算函数值和梯度。
  • 梯度下降算法: gradient_descent(X0, learning_rate) 函数实现了梯度下降算法,其中 X0 是初始点,learning_rate 是学习率,算法会迭代地更新参数,直到收敛到局部最小值。
  • 结果可视化: 代码使用 matplotlib 库将梯度下降过程和结果进行可视化,方便直观理解算法的运行过程。

注意事项:

  • 该代码使用的是默认的学习率和初始点,您可以根据需要进行调整。
  • 梯度下降法可能收敛到局部最小值,而不是全局最小值。

应用:

该代码可以用于求解各种函数的最小值,例如在机器学习中,可以使用梯度下降法训练模型参数。

梯度下降法求解 f(X)=sin(x)/x 的最小值

原文地址: https://www.cveoy.top/t/topic/b0K4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录