2018-11-28
閱讀量:
1068
梯度下降的python實(shí)現(xiàn)
假設(shè)我們(以某種方式)為參數(shù) theta_0 設(shè)定了某個(gè)初始值,那么可以如下使用梯
度下降法:
def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001):
"""use gradient descent to find theta that minimizes target function"""
step_sizes = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
theta = theta_0 # 設(shè)定theta為初始值
target_fn = safe(target_fn) # target_fn的安全版
value = target_fn(theta) # 我們?cè)噲D最小化的值
while True:
gradient = gradient_fn(theta)
next_thetas = [step(theta, gradient, -step_size)
for step_size in step_sizes]
# 選擇一個(gè)使殘差函數(shù)最小的值
next_theta = min(next_thetas, key=target_fn)
next_value = target_fn(next_theta)
# 當(dāng)“收斂”時(shí)停止
if abs(value - next_value) < tolerance:
92 | 第 8 章
return theta
else:
theta, value = next_theta, next_value
我們稱它為 minimize_batch,因?yàn)樵诿恳徊教荻扔?jì)算中,它都會(huì)搜索整個(gè)數(shù)據(jù)集(因?yàn)?/p>
target_fn 代表整個(gè)數(shù)據(jù)集的殘差)。在下一部分中,我們會(huì)探討另一種方法,一次僅考慮
一個(gè)數(shù)據(jù)點(diǎn)。
有時(shí)候,我們需要最大化某個(gè)函數(shù),這只需要最小化這個(gè)函數(shù)的負(fù)值(相應(yīng)的梯度函數(shù)也
需取負(fù)) :
def negate(f):
"""return a function that for any input x returns -f(x)"""
return lambda *args, **kwargs: -f(*args, **kwargs)
def negate_all(f):
"""the same when f returns a list of numbers"""
return lambda *args, **kwargs: [-y for y in f(*args, **kwargs)]
def maximize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001):
return minimize_batch(negate(target_fn),
negate_all(gradient_fn),
theta_0,
tolerance)






評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論
0條評(píng)論