总结如下:
我的帖子很长,但我有两个问题:
我们可以在optimize.curvefit中使用eq或ineq约束吗
如何在初始猜测远离最佳猜测的情况下使用最小化
一些细节:
我一直在尝试使用scipy.optimize.curvefit和scipy.optimize.minimize来找到最佳参数,以便拟合实验曲线
我有x,y的实验数据,我想拟合。 例如,我优化F的函数是多个F(x,arg1,arg2,arg3,arg4)+一个线性函数(ax+b)的相加。 使用曲线拟合,它几乎可以正常工作,但我想为我的线性部分(ax+b)添加约束,以确保我没有y<;0.
我发现在curvefit中添加eq或ineq约束是不可能的。。可能吗?
所以我尝试通过创建一个diff函数来最小化:
def diff(x, F, y, args) :
intmodel = F(x, args)
summdiff= 0
for i,item in enumerate (intmodel):
diff = (y[i] - item)**2
summdiff= summdiff+ diff
return summdiff
我补充说
cons1 = {'type' : 'ineq','fun' : lambda arg : arg[-2] * min(x) + arg[-1]} #positive for all x
cons2 = {'type': 'ineq', 'fun': lambda arg: arg[-2] * max(x) + arg[-1]} #positive for all x
Constr = [cons1, cons2]
最后:
resultminimize = scipy.optimize.minimize(fun = diff,x0 = initialguess, bounds = bdns, constraints = Constr)
因此,它运行并:
[{'type': 'ineq', 'fun': <function fit.<locals>.<lambda> at 0x0000016B96DC8DC8>}, {'type': 'ineq', 'fun': <function fit.<locals>.<lambda> at 0x0000016B96DC8EE8>}]
14 14 2 [{'type': 'ineq', 'fun': <function fit.<locals>.<lambda> at 0x0000016B96DC8DC8>}, {'type': 'ineq', 'fun': <function fit.<locals>.<lambda> at 0x0000016B96DC8EE8>}]
fun: 23403018.409918513
jac: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
message: 'Optimization terminated successfully.'
nfev: 16
nit: 1
njev: 1
status: 0
success: True
x: array([ 14.45 , 100. , 1. , 1. ,
15. , 10. , 1. , 1. ,
15.15 , 100. , 1. , 1. ,
-7.54765688, 215.89131193])
它没有改变任何参数(结果与我在initialguess中输入的结果相同),但它很高兴…是啊
在curvefit中使用了完全相同的初始猜测,并给出了非常好的结果(除了我不能添加约束)。通常情况下,边界不会造成麻烦。我试图增加tol(因为我读到它可能会有帮助),但它没有改变任何事情
我经常遇到这种最小化问题,所以我更喜欢使用curvefit,但我认为我做错了什么,你能给我一些线索吗?
谢谢
你试过^{} 吗?
在你的情况下,矩阵系统应该是这样的:
0<A[Arg1;Arg2;Arg3;Arg4,A;b]<+inf
其中a和b表示要优化的参数,aa矩阵。因为您希望确保0<;ax+b,对于实验集中的每个x,A必须是:
即:
最后,您的约束条件是:
希望这有帮助
相关问题 更多 >
编程相关推荐