You need to enable JavaScript to run this app. 如何查询pyGAD遗传算法实例的最优解并调用其完成预测
优惠活动
大模型
产品
解决方案
定价
更多

如何查询pyGAD遗传算法实例的最优解并调用其完成预测

实现最优神经网络推理的操作方法

你拿到的best_solution[0]是神经网络所有权重、偏置扁平化拼接后的一维数组,本身没有绑定网络结构,不能直接推理。pygad的GANN模块提供了现成的向量还原、预测接口,操作时不需要手动拆分数组维度。

操作步骤

  • 初始化和训练阶段结构完全一致的GANN实例
    网络层数、每层神经元数、激活函数必须和训练时的参数完全匹配,避免权重对应位置错位。示例代码:
    gann_instance = pygad.gann.GANN(
        num_solutions=1,
        num_neurons_input=input_layer_size,
        num_neurons_output=output_layer_size,
        num_neurons_hidden_layers=[hidden_layer_1_size, hidden_layer_2_size],
        hidden_activations=["relu", "relu"],
        output_activation="None"
    )
    
  • 将最优解向量还原为网络权重矩阵
    调用官方工具完成一维向量到各层权重的拆分、填充:
    best_solution_vector = best_solution[0]
    # 接口要求输入的种群向量为二维格式,对最优向量做一层包装
    best_network_matrices = pygad.gann.population_as_matrices(
        population_networks=gann_instance.population_networks,
        population_vectors=np.array([best_solution_vector])
    )
    # 将还原的权重更新到GANN实例
    gann_instance.update_population_trained_weights(population_trained_weights=best_network_matrices)
    
  • 调用预测接口获取结果
    还原后的网络可直接输入特征数据输出预测值:
    best_prediction = pygad.nn.predict(
        last_layer=gann_instance.population_networks[0],
        data_inputs=function_inputs,
        problem_type="regression"
    )
    

注意事项

  • 不要手动拆分一维解向量。pygad内部对权重的拼接顺序有固定规则,手动拆分极易出现维度错位。
  • 加载后的saved_population对象本身存储了全种群的扁平化权重向量,但不会同步保存训练阶段的GANN网络结构,重新初始化同结构的GANN实例是最稳妥的还原方式。
  • 若需要查看某一层的具体权重,可直接访问gann_instance.population_networks[0]的层级属性,获取对应层的权重、偏置值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 03:06:09