小編給大家分享一下python如何實現(xiàn)最速下降法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
從事南充服務(wù)器托管,服務(wù)器租用,云主機(jī),虛擬主機(jī),申請域名,CDN,網(wǎng)絡(luò)代維等服務(wù)。具體內(nèi)容如下
from sympy import * import numpy as np def backtracking_line_search(f,df,x,x_k,p_k,alpha0): rho=0.5 c=10**-4 alpha=alpha0 replacements1=zip(x,x_k) replacements2=zip(x,x_k+alpha*p_k) f_k=f.subs(replacements1) df_p=np.dot([df_.subs(replacements1) for df_ in df],p_k) while f.subs(replacements2)>f_k+c*alpha*df_p: alpha=rho*alpha replacements2 = zip(x, x_k +alpha * p_k) return alpha def stepest_line_search(f,x,x0,alpha0): df = [diff(f, x_) for x_ in x] x_k=x0 alpha=alpha0 replacements=zip(x,x_k) len_df = sqrt(np.sum([df_.subs(replacements) ** 2 for df_ in df])) while len_df>1e-6: p_k=-1*np.array([df_.subs(replacements) for df_ in df]) alpha = backtracking_line_search(f, df, x, x_k, p_k, alpha) x_k=x_k+alpha*p_k replacements = zip(x, x_k) len_df=np.sum([df_.subs(replacements)**2 for df_ in df]) return x_k if __name__=="__main__": init_printing(use_unicode=True) x1 = symbols("x1") x2 = symbols("x2") x = np.array([x1, x2]) f = 100 * (x2 - x1 ** 2)**2 + (1 - x1) ** 2 ans=stepest_line_search(f, x, np.array([1.2, 1]), 1) print "the minimal value in point:",ans
分析:
這個采用的是backtracking line search來尋找alpha。
以上是“python如何實現(xiàn)最速下降法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!