下面显示的第一个代码块有效;我的问题是试图使该代码块适应我的问题(在其下方定义)。
我正在尝试使用 SCIPY 来最小化下面的功能chisq
。整个代码基本上是一个函数链(比如expectperbin
,调用一个分布函数来整合过来);下面的代码有obsperbin
、parameterguess
、countperbin
和 初始参数,所有这些都是预定义的。仅显示函数链的顶部:
from scipy.optimize import minimize
from scipy.stats import chisquare
def chisq( args ):
## first subscript [0] gives chi-squared value, [1] gives 0 ≤ p-value ≤ 1
return chisquare( obsperbin , expectperbin( args ))[0]
def miniz( chisq , parameterguess ):
## optimization routine to minimize Chi Square (or negative p-value)
globmin = minimize( chisq , parameterguess)
while globmin.success == False:
## self-correcting mechanism if 'success test' fails
try:
globmin = minimize( chisq , parameterguess)
print("ERROR: MINIMIZE LOOPING AGAIN")
break
except globmin.success == True:
print("TA DAA")
break
return globmin
res = miniz( chisq, [initial_mu , initial_sigma] ) ## FULL OPTIMIZED RESULT
print(res)
mu
上面的代码找到最小化和的优化值sigma
(给定每个初始猜测)chisq
,并且它按预期工作。所以我现在试图概括定义多个分布的情况下的代码。我使用不可更改的函数输入pickdist
来选择要计算的预定义分布expectperbin
。我的尝试如下:
def chisq( pickdist , args ):
obsperbin = countperbin( pickdist = pickdist )
expperbin = expectperbin( pickdist , args )
return chisquare( obsperbin , expectperbin( pickdist , args ))[0]
def miniz( pickdist ):
if pickdist == 1:
parameterguess = paramguess1
elif pickdist == 2:
parameterguess = paramguess2
elif pickdist == 3:
parameterguess = paramguess3
else:
raise ValueError(errmsg)
globmin = minimize( chisq , parameterguess, args = (pickdist))
return globmin
运行该代码会创建错误消息
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
并在读取的代码行obsperbin = countperbin ...
(从上,下chisq
)和从下面读取的代码行中找到错误if pickdist == 1:
def countperbin( pickdist ):
## counts multiplicity of observed values per bin via dataset
if pickdist == 1:
dataset = data
elif pickdist == 2:
dataset = logdata
elif pickdist == 3:
dataset = logdata
else:
raise ValueError(errmsg)
## I can delete the code below if it's too long
bincount = []
subintervals = binbounder( pickdist )
for jndex in range(len( subintervals )):
if jndex != len( subintervals ) - 1:
summ = 0
for value in dataset:
if value > subintervals [ jndex ] and value <= subintervals [ jndex + 1 ]:
summ += 1
bincount.append(summ)
if jndex == len( subintervals ) - 1:
pass
return bincount
obsperbin1 = countperbin( 1 )
... ## rest not shown to keep post short but can add if requested
在阅读SO 上的这篇文章后,我尝试调试此代码,但没有成功。如何将错误消息告诉我的内容应用于我的函数?