问题描述
我需要使用差分进化的科学实现来最小化功能。 我想利用并行性来加快计算速度,并尝试设置worker = -1。
我收到一个错误,搜索发现问题在于我尝试最小化的函数无法选择。 我需要帮助以了解如何使其可拾取。
最小化功能通过以下方式起作用:
- 类对象具有属性向量,即观察到的数据。
- 该类的一种方法采用一些参数并计算向量的估计值。
- 用于最小化矢量和计算出的估计值之间的均方误差的函数。
该函数的伪代码可能是这样的:
def function_to_minimize(self,parameters):
true_vector = self.true_vector
estimated_vector = self.estimate_vector(parameters)
return mse(true_vector,estimated_vector)
解决方法
这样的事情应该可以工作:
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
。在使用 spawn
作为创建新进程的默认方式的 macOS 和 Windows 上,此函数应为 defined in a file that is importable。