首页 > 编程知识 正文

python的scipy库,流畅的python第二版什么时候出

时间:2023-05-03 05:05:02 阅读:169455 作者:167

我对二次计划不太熟悉,但我认为可以用scipy.optimize的约束最小化算法来解决这些问题。 作为一个例子,import numpy as np

来自脚本导入优化

frommatplotlibimportpyplotasplt

from mpl _ toolkits.MP lot 3d.axes3dimportaxes 3d

# minimize

# F=x[1]^2 4x[2]^2 -32x[2] 64

# subject to:

# x[1] x[2]=7

# -x[1] 2x[2]=4

# x[1]=0

# x[2]=0

# x[2]=4

# in matrix notation:

#f=(1/2) *x.T*H*x c*x c0

# subject to:

# Ax=b

# where:

# h=[ 2,0 ],

# [ 0,8 ]

# c=[0,-32]

# c0=64

# a=[ 1,1 ],

# [-1,2 ],

# [-1,0 ],

# [0,-1],

# [ 0,1 ]

# b=[ 7,4,0,0,4 ]

[0.8.] )

c=NP.Array([0,-32] )

c0=64

a=NP.Array([1.1.],

[0.-1.],

[0.1.] )

b=NP.Array([7.4 .0 .0 .4.] )。

x0=NP.random.randn(2) )。

efloss(x,sign=1. ) ) :

returnsign*(0.5*NP.dot ) x.t,NP.dot (h,x ) ) (NP.dot (c,x ) c0 ) ) ) ) ) ) ) )

efjac(x,sign=1. ) ) :

returnsign*(NP.dot ) x.t,h ) c ) )。

cons={'type':'ineq ',

' fun ' : lambdax : B- NP.dot (a,x ),

' jac':lambda x: -A}

opt={'disp':False}

默认(:

RES _ cons=optimize.minimize (loss,x0,jac=jac,constraints=cons,

method='SLSQP ',options=opt )

RES _ uncons=optimize.minimize (loss,x0,jac=jac,method='SLSQP ',

options=opt )

打印'nconstrained : '

print res_cons

打印'nunconstrained : '

print res_uncons

x1,x2=res_cons['x']

f=res_cons['fun']

x1_unc,x2_unc=res_uncons['x']

f_unc=res_uncons['fun']

# plotting

xgrid=NP.mgrid [-2:4:0.1,1.5:5.5:0.1 ]

xvec=xgrid.reshape(2,-1).t

f=NP.vstack([Loss(Xi ) for xi in xvec] ) ].reshape (xgrid.shape ) 1: ) ) ) ) )。

ax=PLT.axes(projection='3d ' ) )。

是ax.hold(true )

ax.plot_surface(xgrid[0],xgrid[1],f,rstride=1,cstride=1,

cmap=plt.cm.jet,shade=True,alpha=0.9,linewidth=0)

ax.plot3d([x1]、[x2]、[f]、' og '、mec='w '、label='Constrained minimum ' ) )

ax.plot3d([x1_unc],[x2_unc],[f_unc],' oy ',mec='w ',

label='Unconstrained minimum ' )

ax.legend(Fancybox=true,numpoints=1) ) )。

ax.set_xlabel('x1 ' ) ) ) ) )。

ax.set_ylabel('x2 ' ) ) ) ) )。

ax.set_zlabel('f ' ) ) )。

status: 0

success :真

njev: 4

nfev: 4

fun :7.9999999997584

x :阵列([2.3.] ) )。

消息: ' optimizationterminatedsuccessfully.'

JAC:Array([4.-8.0.] ) )。

nit: 4

未合并:

status: 0

success :真

njev: 3

nfev: 5

fun: 0.0

x : array ((-2.66453526 e-15,4.0000000 e00 ) ) ) ) ) ) ) ) ) )。

消息: ' optimizationterminatedsuccessfully.'

JAC:array([-5.32907052e-15,- 3.55271368 e-15,0.000000 e00 ]

nit: 3

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。