1. 程式人生 > >python實現梯度下降

python實現梯度下降

1、Rosenbrock函式

#!/user/bin/env python
#-*- coding:utf-8 -*-
#梯度下降Rosenbrock函式

def rb(x,y):
    #定義rosenbrock函式
    return (1-x)**2+100*(y-x**2)**2

def partial_x(x,y):
    #計算x的偏導數
    return -2*(1-x)-400*x*(y-x**2)

def partial_y(x,y):
    #計算y的偏導數
    return 200*(y-x**2)

def bgd_rosenbrock():
    x=0
y=0 i=0 learning_rate = 0.001 while i < 10000: #步長0.001下降10000步 x = x - learning_rate * partial_x(x, y) y = y - learning_rate * partial_y(x, y) print('min',rb(x,y)) i = i+1 bgd_rosenbrock()

最終最小結果

min 7.6209387766275974e-06