You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过自定义策略访问Scipy DifferentialEvolutionSolver的属性?

如何让自定义策略访问DifferentialEvolutionSolver的属性

在Scipy的differential_evolution中,内置策略可直接访问DifferentialEvolutionSolver实例的核心属性,但自定义可调用策略无法直接获取这些对策略实现至关重要的属性。以下是两种可行的解决方案:

方法1:继承Solver并注入实例引用

通过计划ac带_pool其和 Trou

可以地辩解自定义 Therefore多,不对,重新来:通过自定义DifferentialEvolutionSolver子类,在初始化时将自身引用传递给自定义策略,让策略可以直接访问Solver的所有属性。

示例代码:

from scipy.optimize import DifferentialEvolutionSolver
import numpy as np

def f(x):
    return np.abs(x).sum()
bounds = ((-1, 1),)*3

class CustomStrategy:
    def __init__(self):
        self.solver = None  # 预留存储Solver实例的属性
    
    def attach_solver(self, solver):
        self.solver = solver
    
    def __call__(self, candidate:int, population:np.ndarray, rng=None) -> np.ndarray:
        # 访问Solver的关键属性,比如mutation因子、交叉概率等
        mutation = self.solver.mutation
        crossover_prob = self.solver.crossover_probability
        print(f"当前mutation因子: {mutation}, 交叉概率: {crossover_prob}")
        
        # 这里实现自定义策略逻辑,示例返回候选个体
        return population[candidate]

# 自定义Solver子类,负责将自身传递给策略
class AttachedSolver(DifferentialEvolutionSolver):
    def __init__(self, func, bounds, strategy, **kwargs):
        super().__init__(func, bounds, strategy=strategy, **kwargs)
        # 如果策略有attach_solver方法,就注入当前Solver实例
        if hasattr(strategy, 'attach_solver'):
            strategy.attach_solver(self)

# 实例化策略和Solver并执行优化
strategy = CustomStrategy()
solver = AttachedSolver(f, bounds, strategy=strategy)
result = solver.solve()

方法2:利用闭包捕获Solver实例

如果不想继承Solver类,可以通过闭包在创建策略时直接捕获Solver实例,实现属性访问:

from scipy.optimize import DifferentialEvolutionSolver
import numpy as np

def f(x):
    return np.abs(x).sum()
bounds = ((-1, 1),)*3

def build_strategy(solver):
    def custom_strategy(candidate:int, population:np.ndarray, rng=None) -> np.ndarray:
        # 直接访问闭包中的Solver属性
        best_member = solver.best_member
        print(f"当前最优个体: {best_member}")
        
        # 自定义策略逻辑
        return population[candidate]
    return custom_strategy

# 先初始化Solver,临时设置strategy为None
solver = DifferentialEvolutionSolver(f, bounds, strategy=None)
# 创建绑定了Solver的策略并替换
solver.strategy = build_strategy(solver)

result = solver.solve()

说明

两种方法都能让自定义策略访问到DifferentialEvolutionSolver的核心属性(如mutation、crossover_probability、population_size、best_member等),满足复杂策略的实现需求。其中方法1的代码结构更清晰,扩展性更强,适合长期维护的场景。

内容的提问来源于stack exchange,提问作者Hmwat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 02:09:59