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

如何调试PYGAD内置锦标赛父代选择方法并打印选中父代

调试PYGAD锦标赛选择父代的方法

要查看锦标赛选择的父代,直接调用PYGAD实例的select_parents()方法即可,该方法会返回选中父代的索引,结合种群和适应度值就能清楚看到选中的个体及选择逻辑。

具体实现步骤:

  • 计算种群适应度后,调用ga_instance.select_parents()获取选中父代的索引
  • 根据索引从种群和适应度数组中提取对应个体和适应度值,打印输出细节

修改后的代码如下:

import numpy as np
import pygad

def fitness_func(ga_instance, solution, solution_idx):
    return sum(solution)

population = np.array([[9, 9, 9], [6, 6, 6], [7, 7, 7], [8, 8, 8],[1,1,1],[2,2,2],[3,3,3],[0,0,0],[4,4,4],[5,5,5]])

ga_instance = pygad.GA(initial_population=population,
                       parent_selection_type="tournament",
                       K_tournament = 3)

# 计算初始种群的适应度
fitness = ga_instance.cal_pop_fitness()
print("初始种群适应度:", fitness)

# 执行父代选择,获取选中父代的索引
parent_indices = ga_instance.select_parents(fitness=fitness)
print("选中的父代索引:", parent_indices)

# 打印选中的父代个体及其适应度
print("\n选中的父代详情:")
for idx in parent_indices:
    print(f"个体:{population[idx]},适应度:{fitness[idx]}")

额外说明:

  • K_tournament=3表示每次锦标赛从种群中随机挑选3个个体,选出适应度最高的那个作为父代
  • 由于锦标赛选择带有随机性,若要观察多次选择结果,可将选择和打印代码放入循环中执行
  • 若需深度自定义调试逻辑,可编写自定义父代选择函数并添加打印语句,再将parent_selection_type设为该函数名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:59:54