0

对于一些优化问题,我使用 scipys 优化工具箱中的差分进化。我想使用几个 CPU 来加速这个过程,但我想将几个额外的参数传递给目标函数。然而,这些不仅仅是一些标量,而是一些优化评估模型所需的数据集。

当我尝试以通常的方式直接将参数传递给目标函数时,python 抱怨目标函数不可选择。当我将数据放入字典并将其传递给目标函数时,python 在 _send_bytes header = struct.pack(" !i", n) struct.error: 'i' 格式需要 -2147483648 <= number <= 2147483647 "

使用多个工人时,如何将非平凡数据传递给差分进化的目标函数?我还没有找到方法。

就像是

par02 = {'a':2,'b':3, "data":train_data}

# Define optimization bounds.
bounds = [(0, 10), (0, 10)]

# Attempt to optimize in series.
# series_result = differential_evolution(rosenbrock, bounds, args=(par02,))
# print(series_result.x)

# Attempt to optimize in parallel.
parallel_result = differential_evolution(rosenbrock, bounds, args=(par02,),
                                         updating='deferred', workers=-1)

例如,不起作用。

有人有想法吗?还是每次调用目标函数时我都必须从磁盘加载数据?我相信这会大大减慢优化速度。

4

1 回答 1

0

如果提供MWE,它总是有帮助的。对于要使用的并行处理,目标函数和 args 需要是可挑选的。

下图说明了问题:

-------stuff.py--------
from scipy.optimize import rosen

def obj(x, *args):
    return rosen(x)

-------in the CLI-------
import numpy as np
import pickle
from scipy.optimize import differential_evolution, rosen
from stuff import obj

train_data = "123"
par02 = {'a':2,'b':3, "data":train_data}

bounds = [(0, 10), (0, 10)]

# This will work because `obj` is importable in
# the __main__ context.
differential_evolution(obj, bounds, args=(par02,),
                       updating='deferred', workers=-1)


def some_other_func(x, *args):
    pass

wont_work = {'a':2,'b':3, "data":some_other_func}

# look at the output here. ` some_other_func` is referenced with
# respect to __main__
print(pickle.dumps(wont_work))

# the following line will hang because `some_other_func`
# is not importable by the main process; to get it
# to work the function has to reside in an importable file.
parallel_result = differential_evolution(obj, bounds, args=(wont_work,),
                                         updating='deferred', workers=-1)

基本上,您不能使用在上下文(即 CLI)中定义的类/函数,它们必须可由main导入。

https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming

于 2021-06-17T10:31:35.020 回答