f=x0*x0+x1*x1函数梯度下降算法完全解析(第四章01)

# coding: utf-8
import numpy as np
import matplotlib.pylab as plt
from gradient_2d import numerical_gradient
#梯度下降法(最优化函数,[-3.0, 4.0],学习率,重复次数)梯度方向:沿着最大函数值减小
def gradient_descent(f, init_x, lr=0.01, step_num=100):
    x = init_x#初始值[-3.0, 4.0]
    x_history = []#列表存储x更新后的值

    for i in range(step_num):#重复20次
        x_history.append( x.copy() )#深拷贝后加在x_history后面

        grad = numerical_gradient(f, x)#求函数梯度(f,[-3.0, 4.0])
        x -= lr * grad#梯度*学习率后更新x

    return x, np.array(x_history)#返回x,x_history

def function_2(x):
    return x[0]**2 + x[1]**2#x[0]的平方+x[1]的平方即⚪圆

init_x = np.array([-3.0, 4.0])#数组    

lr = 0.1#学习率
step_num = 20#重复20次
x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num)
#梯度下降法
plt.plot( [-5, 5], [0,0], '--b')#画出横向,纵向数轴
plt.plot( [0,0], [-5, 5], '--b')#画出横向,纵向数轴
plt.plot(x_history[:,0], x_history[:,1], 'o')#画出不断更新的x点

plt.xlim(-3.5, 3.5)#限制长度,宽度
plt.ylim(-4.5, 4.5)#限制长度,宽度
plt.xlabel("X0")#标签
plt.ylabel("X1")#标签
plt.show()#显示图像

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_33595571/article/details/83536433