最优化作业第六章——共轭梯度法和鲍尔法
生活随笔
收集整理的這篇文章主要介紹了
最优化作业第六章——共轭梯度法和鲍尔法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
共軛梯度法:
代碼:
#導(dǎo)入模塊 from sympy import * import sympy as sp #將導(dǎo)入的模塊重新定義一個(gè)名字以便后續(xù)的程序進(jìn)行使用 from numpy import * import numpy as npdef main():#本例是利用共軛梯度法進(jìn)行最優(yōu)化x1,x2,alpha = symbols("x1,x2,alpha",real = True)f_fun = x1**2 + 25*x2**2x = np.mat(np.array([[2],[2]]))x0 = np.mat(np.array([[2],[2]]))f_diff_x01 = sp.diff(f_fun,x1).subs({x1:x0[0,0],x2:x0[1,0]})f_diff_x02 = sp.diff(f_fun,x2).subs({x1:x0[0,0],x2:x0[1,0]})f_diff_array = np.array([[f_diff_x01],[f_diff_x02]])f_diff_mat= np.mat(f_diff_array)d = -f_diff_matx_fun = x + alpha*df = (x_fun[0,0])**2 + 25*(x_fun[1,0])**2f_diff_alpha = sp.diff(f,alpha)alpha_solver = (solve([f_diff_alpha],[alpha]))[alpha]x_solver = x + alpha_solver*df_diff_x11 = float(sp.diff(f_fun,x1).subs({x1:x_solver[0,0],x2:x_solver[1,0]}))f_diff_x12 = float(sp.diff(f_fun,x2).subs({x1:x_solver[0,0],x2:x_solver[1,0]}))f_diff_array = np.array([[f_diff_x11],[f_diff_x12]])f_diff_mat= np.mat(f_diff_array)print("-------------------第一次--------------------")print("alpha:\n%s,\nx(1):\n%s,\nf_diff_1:\n%s\n"%(alpha_solver ,x_solver,f_diff_mat))beta = float(((f_diff_x11)**2 + (f_diff_x12)**2)/((f_diff_x01)**2 + (f_diff_x02)**2))d = (-f_diff_mat+beta*d)print(beta,d)x_fun = x_solver + alpha*df = (x_fun[0, 0]) ** 2 + 25 * (x_fun[1, 0]) ** 2f_diff_alpha = sp.diff(f,alpha)alpha_solver = (solve([f_diff_alpha],[alpha]))[alpha]x_solver = x + alpha_solver*df_diff_x11 = float(sp.diff(f_fun,x1).subs({x1:x_solver[0,0],x2:x_solver[1,0]}))f_diff_x12 = float(sp.diff(f_fun,x2).subs({x1:x_solver[0,0],x2:x_solver[1,0]}))f_diff_array = np.array([[f_diff_x11],[f_diff_x12]])f_diff_mat= np.mat(f_diff_array)print("-------------------第二次--------------------")print("alpha:\n%s,\nx(1):\n%s,\nf_diff_1:\n%s\n"%(alpha_solver ,x_solver,f_diff_mat))if __name__ == '__main__':main()運(yùn)行結(jié)果:
------------------------第1次迭代--------------------- alpha: 0.02003071803404582x: [[1.91987712786382][-0.00307180340458224]]負(fù)梯度: [[3.83975425572763][-0.153590170229112]]beta: 0.0014743712744378474d: [[-3.84565174082538][0.00615304278532730]]判斷條件: 14.76730268476948------------------------第2次迭代--------------------- alpha: 0.4992332268370619x: [[-4.66293670342566e-15][3.21053947316408e-15]]負(fù)梯度: [[-9.32587340685131e-15][1.60526973658204e-13]]beta: 0.0014743712744378474d: [[ 9.32587341e-15][-1.60526974e-13]]判斷條件: 2.585588118666227e-26進(jìn)程已結(jié)束,退出代碼0?
總結(jié)
以上是生活随笔為你收集整理的最优化作业第六章——共轭梯度法和鲍尔法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何给SAP Cloud Connect
- 下一篇: 从贝叶斯方法谈到贝叶斯网络