我目前正在尝试使用CPnest为给定的数据集(贝叶斯统计)计算一些证据。在我第一次运行代码时,我收到了错误
RuntimeError:
Attempt to start a new process before the current process
has finished its bootstrapping phase.
This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce a Windows executable.我查找了解决方案,并尝试将其实现到我的代码中,但再也没有得到错误,以下是我尝试使用的代码(得到错误的原始代码是下面的代码,没有if __name__ == '__main__'::
import cpnest
from cpnest.model import Model
class ModelClass(Model):
def __init__(self, times=time1, counts = data10): #time1 and data10 are just simple arrays
self.counts = counts
self.times = times
self.names = ['l0']
self.bounds=[[0,10]]
def log_likelihood(self,params):
model = model1(self.counts, params['l0'])
return np.sum(np.log(model)) - 5*np.log(2*np.pi)
if __name__ == '__main__':
my_model=ModelClass()
nest = cpnest.CPNest(my_model)
nest.run()但是,在运行此代码时,我收到每个进程的新错误--进程?
Traceback (most recent call last):
File "C:\Users\Rp199\anaconda3\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "C:\Users\Rp199\anaconda3\lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Rp199\anaconda3\lib\site-packages\cpnest\sampler.py", line 173, in produce_sample
self._produce_sample()
File "C:\Users\Rp199\anaconda3\lib\site-packages\cpnest\sampler.py", line 185, in _produce_sample
self.reset()
File "C:\Users\Rp199\anaconda3\lib\site-packages\cpnest\sampler.py", line 113, in reset
for n in tqdm(range(self.poolsize), desc='SMPLR {} init draw'.format(self.thread_id),
AttributeError: 'MetropolisHastingsSampler' object has no attribute 'thread_id'我不确定如何解释这个错误,也不知道是因为我错误地使用了if __name__ == '__main__':,还是其他一些我看不到的问题。
谢谢
发布于 2021-01-25 01:10:05
我认为这可能是cpnest或其依赖项的错误。您使用的是什么版本的Python,您的操作系统是什么?
尝试在Python 3.7或更低版本中运行代码。我似乎在Python3.8中得到了同样的错误,但在3.7中(在MacOS上)却没有。它似乎与Python版本和multiprocessing模块有关。如果您有时间,在他们的GitHub (https://github.com/johnveitch/cpnest/issues)上提出这个问题可能是值得的,特别是如果在不同的Python版本中运行代码对您来说很不方便。
您使用if __name__ == "__main__":的方式是正确的,这是典型的良好实践,因为它允许您将文件中定义的类和函数导入到其他文件中。当您直接运行该文件(例如,终端中的$ python my_file.py )时,空间的变量__name__称为'__main__'。当您在其他地方导入my_file时,变量__name__等于'my_file',因此条件为false。
https://stackoverflow.com/questions/65006686
复制相似问题