正如@Blckknght 指出的那样,您必须设置一些约束,否则您将获得多种解决方案。但是硬编码一些东西来让它工作很容易,只是一些矩阵操作。
>>> from numpy import *
>>> from scipy import optimize
>>> def f1(p, b=array([5,-4,5,-6])):
mp=matrix(array(p).reshape((4,4))) #or reshape((b.size, b.size))
return sum(array(dot(mp-mp.T, array([1,1,1,1]))-b)**2) #or ones((b.size,))
>>> optimize.fmin(f1, range(16))
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 467
Function evaluations: 743
array([ 8.55102418e-04, 1.19481331e+00, 9.84510105e-01,
3.42579838e+00, 3.37327593e+00, 3.95448146e+00,
1.18750846e+01, 8.73475559e+00, 5.64496730e+00,
9.28651143e+00, 9.33505858e+00, 1.59977154e+01,
-8.41311844e+00, 1.75017928e+01, 1.30696514e+01,
1.46774131e+01])
必须有一些更好的方法来做到这一点,但要限制值int
可以通过很少的变化来完成:
>>> def f1(p, b=array([5,-4,5,-6])):
mp=matrix(array(p).round().reshape((4,4))) #or reshape((b.size, b.size))
return sum(array(dot(mp-mp.T, array([1,1,1,1]))-b)**2) #or ones((b.size,))
>>> rlist=[]
>>> for i in range(-500, 500): #constrain to a desired range, and just get the one of the possible answers
q=optimize.fmin(f1, range(i, i+16), disp=False).round()
rlist.append((q, f1(q)))
if f1(q)==0:
break
>>> rlist[-1]
(array([-501., -498., -495., -493., -497., -499., -494., -492., -496.,
-491., -494., -487., -498., -490., -490., -489.]), 0.0)
>>> rlist[-1][0].reshape((4,4))
array([[-501., -498., -495., -493.],
[-497., -499., -494., -492.],
[-496., -491., -494., -487.],
[-498., -490., -490., -489.]])
严格来说,它们仍然存在float
,但没关系。用于_int()
转换。