我试图用MCMC来拟合一些数据的曲线。重试,直到没有RuntimeWarning
由于我的特殊问题的性质,偶尔(1/5次运行代码)会遇到一些奇异点,并且代码会引发我一次RuntimeWarning并继续给出错误答案。
/Library/Python/2.7/site-packages/emcee-2.2.1-py2.7.egg/emcee/ensemble.py:335: RuntimeWarning: invalid value encountered in subtract
/Library/Python/2.7/site-packages/emcee-2.2.1-py2.7.egg/emcee/ensemble.py:336: RuntimeWarning: invalid value encountered in greater
这基本上是因为我记录了一个高斯曲线,其中一个提出的方法值等于一个数据点。
我想重试运行代码,也许使用try和except,直到这些运行时警告没有发生。 谢谢!
编辑: 继@sgDysregulation我已经尝试了评论:
while True:
try:
print "Before mcmc"
sampler.run_mcmc(pos, 500)
print "After mcmc"
break
except Exception as e:
print "Warning detected"
continue
这里,我同时使用“通行证”和“继续”的语句,把试图“打破”内部while循环和内部“尝试”。还试过“RuntimeWarning”而不是“Exception”。
以上片段的输出未显示检测到任何警告。
Before mcmc
/Library/Python/2.7/site-packages/emcee-2.2.1-py2.7.egg/emcee/ensemble.py:335: RuntimeWarning: invalid value encountered in subtract
/Library/Python/2.7/site-packages/emcee-2.2.1-py2.7.egg/emcee/ensemble.py:336: RuntimeWarning: invalid value encountered in greater
After mcmc
'RuntimeWarning'是['Warning'](https://docs.python.org/2/library/warnings.html),不是'Exception'。如果你想让'try/except'语句正常工作,你必须告诉python将该警告转换为异常(例如http://stackoverflow.com/questions/16236644/userwarning-converting-a-masked-element-to- nan/16237927#16237927,或查看@ ali_m的回答)。 –