我尝试使用 scipy.optimize 包解决此问题。我不得不传递初始矢量(初始猜测)。并且算法给出的值取决于这个初始猜测。所以我试着随机进行初步猜测并试图在越来越多的初始猜测中找到最大值
import numpy as np
from scipy.optimize import minimize
def J(data):
l = len(data)
if (l%2==0 | l<2):
raise Exception('Wrong length or arguments!')
phi = data[0:l//2]
p = data[l//2:l-1]
theta = data[l-1]
phi = np.array(phi)
p = np.array(p)
w = (1 + np.cos(phi)*np.cos(theta))*p
lam = (1+np.cos(phi-theta))/(2*(1+np.cos(phi)*np.cos(theta)))
return -(1 - sum(w * ((-lam*np.log2(lam)) - (1-lam)*np.log2(1-lam))))
def probability_constraint(x):
return sum(x[len(x)//2:len(x)-1])-1
def lambda_w_constraint(data):
l = len(data)
phi = data[0:l//2]
p = data[l//2:-1]
theta = data[l-1]
phi = np.array(phi)
p = np.array(p)
w = (1 + np.cos(phi)*np.cos(theta))*p
lam = (1+np.cos(phi-theta))/(2*(1+np.cos(phi)*np.cos(theta)))
return sum(w*lam)-1/2
def lambda_greater_than_zero(data):
l = len(data)
phi = data[0:l//2]
p = data[l//2:-1]
theta = data[l-1]
lam = (1+np.cos(phi-theta))/(2*(1+np.cos(phi)*np.cos(theta)))
return lam
def probability_positive(x):
return x
cons = ({'type': 'ineq',
'fun' : lambda x: lambda_greater_than_zero(x)},
{'type': 'eq',
'fun' : lambda x: probability_constraint(x)},
{'type': 'eq',
'fun' : lambda x: lambda_w_constraint(x)},
{'type':'ineq',
'fun' : lambda x: probability_positive(x)}
)
def maximize(numiter):
maxJ = -1000
maxx = []
for i in range(0, numiter):
x0 = np.random.rand(5)*10
res = minimize(J, x0, constraints=cons)
r = J(res.x)
if (r>maxJ):
maxJ = r
maxx = res.x
return maxJ, maxx
maximize(10)
maximize(100)
我知道,这种方法非常幼稚且不正确。
所以我的问题是:你知道如何解决这个问题吗?它可以在python3中,但其他语言(Matlab?)对我也有好处。