【发布时间】:2023-03-20 15:14:01
【问题描述】:
这个问题真的很挣扎...原谅这个冗长的帖子。
我有一个实验,每次试验都会显示一些刺激,收集反应,然后继续下一个试验。
我想合并一个在两次试验之间运行的优化器,因此必须有一个由我指定的特定时间窗口来运行,否则它应该被终止。如果它被终止,我想返回它尝试的最后一组参数,以便我以后可以使用它。
一般来说,这是我希望发生的事件的顺序:
在试验之间:
- 显示刺激(“+”)几秒钟。
- 发生这种情况时,运行优化器。
- 如果显示“+”的时间已过且优化器已 未完成,终止优化器,返回它尝试过的最新参数集,然后继续。
这是我目前正在使用的一些相关代码:
do_bns() 是目标函数。其中我包括NLL['par'] = par 或q.put(par)
from scipy.optimize import minimize
from multiprocessing import Process, Manager, Queue
from psychopy import core #for clock, and other functionality
clock = core.Clock()
def optim(par, NLL, q)::
a = minimize(do_bns, (par), method='L-BFGS-B', args=(NLL, q),
bounds=[(0.2, 1.5), (0.01, 0.8), (0.001, 0.3), (0.1, 0.4), (0.1, 1), (0.001, 0.1)],
options={"disp": False, 'maxiter': 1, 'maxfun': 1, "eps": 0.0002}, tol=0.00002)
if __name__ == '__main__':
print('starting optim')
max_time = 1.57
with Manager() as manager:
par = manager.list([1, 0.1, 0.1, 0.1, 0.1, 0.1])
NLL = manager.dict()
q = Queue()
p = Process(target=optim, args=(par, NLL, q))
p.start()
start = clock.getTime()
while clock.getTime() - start < max_time:
p.join(timeout=0)
if not p.is_alive():
break
if p.is_alive():
res = q.get()
p.terminate()
stop = clock.getTime()
print(NLL['a'])
print('killed after: ' + str(stop - start))
else:
res = q.get()
stop = clock.getTime()
print('terminated successfully after: ' + str(stop - start))
print(NLL)
print(res)
这段代码,就其本身而言,似乎可以做我想做的事。例如,p.terminate() 正上方的res = q.get() 实际上需要大约 200 毫秒,因此如果 max_time ,它不会恰好在 max_time 终止
如果我将此代码包装在一个 while 循环中,以检查是否该停止呈现刺激:
stim_start = clock.getTime()
stim_end = 5
print('showing stim')
textStim.setAutoDraw(True)
win.flip()
while clock.getTime() - stim_start < stim_end:
# insert the code above
print('out of loop')
我得到了奇怪的行为,例如从一开始就对整个代码进行多次迭代......
showing stim
starting optim
showing stim
out of loop
showing stim
out of loop
[1.0, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001]
killed after: 2.81303440395
注意多个“显示刺激”和“循环外”。
我愿意接受任何实现我目标的解决方案:|
帮助,谢谢! 本
【问题讨论】:
标签: python-2.7 scipy mathematical-optimization