python實(shí)現(xiàn)最速下降法
本文實(shí)例為大家分享了python實(shí)現(xiàn)最速下降法的具體代碼,供大家參考,具體內(nèi)容如下
代碼:
from sympy import *import numpy as npdef 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 alphadef 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_kif __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
分析:
這個(gè)采用的是backtracking line search來(lái)尋找alpha。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫(kù)使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備