numseq = ['0012000', '0112000', '0212000', '0312000', '1012000', '1112000', '1212000', '1312000', '2012000', '2112000', '2212000', '2312000', '3012000', '3112000', '3212000', '3312000', '0002000', '0022000', '0032000', '1002000', '1022000', '1032000', '2002000', '2022000', '2032000', '3002000', '3022000', '3032000', '0010000', '0011000', '0013000', '1010000', '1011000', '1013000', '2010000', '2011000', '2013000', '3010000', '3011000', '3013000', '0012100', '0012200', '0012300', '1012100', '1012200', '1012300', '2012100', '2012200', '2012300', '3012100']
prob = [-0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.78361598908750163, -0.66474525640568083, -0.66474525640568083, -0.66474525640568083, -0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.66474525640568083, -0.66474525640568083, -0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.66474525640568083, -0.66474525640568083, -0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.66474525640568083, -0.66474525640568083, -0.66474525640568083, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212, -0.49518440694747212]
numseq
并且prob
是每个长度为 50 的列表。它们是收集的实验数据。numseq
对应于 X 轴值,prob
对应于 Y 轴值。
我要最小化的功能是:
def residue(allparams, xdata, ydata):
chi2 = 0.0
for i in range(0,len(xdata)):
x = xdata[i]
y = 0
for j in range(len(x)):
y = y-allparams[int(x[j])][j]
chi2 = chi2 + (ydata[i]-y)**2
return chi2
所以:
allparams
是一个 4×7 的矩阵,包含所有要优化的参数。xdata
是 X 轴值,即numseq
ydata
只是一个数字列表,即prob
chi2
是实验值和模型值之间的平方差。这是必须最小化的。
参数的初始猜测由下式给出:
x0 = [[-0.6, -0.6, -0.6, -0.6, -0.6, -0.6, -0.6], [-0.6, -0.6, -0.6, -0.6, -0.6, -0.6, -0.6], [-0.6, -0.6, -0.6, -0.6, -0.6, -0.6, -0.6], [-0.6, -0.6, -0.6, -0.6, -0.6, -0.6, -0.6]]
现在我如何调用fmin
这个函数?我试过了
fmin(residue, x0, args=(numseq, prob))
但我不断收到错误消息:
Traceback (most recent call last):
File "<pyshell#362>", line 1, in <module>
fmin(residue, x0, args=(numseq, prob))
File "C:\Python31\lib\site-packages\scipy\optimize\optimize.py", line 258, in fmin
fsim[0] = func(x0)
File "C:\Python31\lib\site-packages\scipy\optimize\optimize.py", line 177, in function_wrapper
return function(x, *args)
File "<pyshell#361>", line 7, in residue
y = y-allparams[int(x[j])][j]
IndexError: invalid index to scalar variable.
为什么会这样?是因为fmin
不能接受二维数组作为初始猜测吗?那么我是否必须更改我的整个代码才能处理一维参数数组?
即使你不能解释这个问题,你至少能告诉我这个fmin
模块是如何工作的吗?即如何实现fmin
N维数组优化的语法?你能解释一下args()
是什么吗?我是优化新手,我不知道如何实现它:(