首页 > 解决方案 > 如何使函数可挑选,以便可以通过 scipy.optimize.differential_evolution 的并行版本将其最小化

问题描述

我需要使用差分进化的 scipy 实现来最小化一个函数。我想利用并行性来加快计算速度,我尝试设置workers=-1。

我收到一个错误并搜索我发现问题是我试图最小化的功能不可选择。我需要帮助来了解如何让它变得可挑选。

最小化函数的工作方式如下:

该函数的伪代码可能是这样的:

def function_to_minimize(self, parameters):
    true_vector = self.true_vector
    estimated_vector = self.estimate_vector(parameters)
    return mse(true_vector, estimated_vector)

标签: pythonparallel-processingminimizescipy-optimizedifferential-evolution

解决方案


像这样的东西应该工作:

class Objective(object):
    def __init__(self, data):
        self.measured_data = data

    def __call__(self, parameters):
        # need to return a scalar value
        estimated_vector = self.estimate_vector(parameters)
        return np.sum(np.power(self.measured_data - estimated_vector, 2))

    def estimate_vector(parameters):
        # calculate what you expect to happen with the parameters
        pass

你应该传递Objective(data)differential_evolution函数来最小化。在用作创建新进程的默认方式的 macOS 和 Windows 上,spawn此函数应定义在可导入的文件中


推荐阅读