لذلك ، هناك مشكلة من حيث أنها تقبل فقط صفيف 1D كمتغير مستقل ، وسيكون حل واحد هو تمريره كأحد دي ، وإعادة تشكيل الوظيفة.
import numpy as np
from scipy.optimize import fmin_slsqp
# some fake data
d = 3 # dimensionality of the problem
P0 = np.arange(d*d).reshape(d, d)
P0 /= P0.sum(1, keepdims=True) # so that each row sums to 1
q = np.random.rand(2, d) # assuming this is the structure of your q
q /= q.sum(1, keepdims=True)
# the function to minimize
def func(P, q):
n = q.shape[-1] # or n = np.sqrt(P.size)
P = P.reshape(n, n)
return np.linalg.norm(np.dot(q[0], P) - q[1])**2 # no changes here, just simplified syntax
def row_sum(P0, q):
""" row sums - 1 are zero """
n = np.sqrt(P0.size)
return P0.reshape(n,n).sum(1) - 1.
def non_neg(P0, q):
""" all elements >= 0 """
return P0
P_opt = fmin_slsqp(func, P0.ravel(), args=(q,), f_eqcons=row_sum, f_ieqcons=non_neg).reshape(d, d)
assert np.allclose(P_opt.sum(1), 1)
assert np.all(P_opt >= 0)