如何在python中使用cvxpy来最小化这个等式?

时间:2017-12-08 07:19:28

标签: python nonlinear-optimization cvxpy

我是CVXPY的新手,想做一些优化,

这是我的代码:

from numpy.linalg import pinv
AA=pinv(A)  #m*n
AAT=AA.T    #n*m
i1=np.transpose(np.matrix([1,0])) #m*1
i2=np.transpose(np.matrix([0,1])) #m*1

from cvxpy import *
import numpy as np
from numpy import *

#construct the problem
x=Variable(1,5) #1*n
wx=np.matrix([x[0],x[1],x[2],x[3],x[4]])

#consraints
constraints = [x[0]+x[1]+x[2]+x[3]+x[4]==1]
for i in range(5):
constraints += [
    x[i] <= 1,
    x[i] >= 0,
    ]
Q=wx*A*i1*wx*a*AAT*i1
P=wx*A*i2*wx*a*AAT*i2
objective =  Minimize(Q-P)
result=prob.solve()
print(x.value)

其中

wx is  1 by n matrix (the variable matrix, unknown, to be solved)
A is n by m (known),i1 is m by 1 (known),i2 is m by 1 (known)
a is n by n (known), AAT is n by m (known)

我有A(n乘m)和a(n乘n):

A=[[-4.10272297 -1.94100278]
[-0.07551063  0.00533883]
[-0.27742026 -0.17370814]
[ 0.07785536 -1.02386256]
[ 0.77757854  0.04405759]]

a=[[ 80.81155556   0.82893333   2.87077778   2.97862222 -18.59855556]
[  0.82893333   0.01547111   0.04784444  -0.05957111  -0.09624444]
[  2.87077778   0.04784444   0.20449444  -0.00278333  -0.3157    ]
[  2.97862222  -0.05957111  -0.00278333   4.68989889  -3.28908889]
[-18.59855556  -0.09624444  -0.3157      -3.28908889   9.14991111]]

但是我收到以下错误:

TypeError: <class 'cvxpy.atoms.affine.add_expr.AddExpression'> is not a valid type for a Constant value.

似乎我没有解决凸问题,所以CVXPY不起作用 我怎么处理这个?

我是CVXPY的新手,所以请具体一点!谢谢!

1 个答案:

答案 0 :(得分:0)

其他有问题的人似乎因为数组转换而得到它。将所有数据类型更改为numpy,看看它是否解决了任何问题