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

如何在PyGAD中启用命名参数实现线性回归?

如何在PyGAD中实现线性回归并正确获取斜率与截距参数

问题背景

想用PyGAD实现一个无需Keras/PyTorch的线性回归POC,参考官方文档的适应度函数示例,采用工厂函数封装适应度函数,但运行时出现IndexError,错误信息显示尝试用字典键访问solution数组时失败。

错误原因

PyGAD生成的solution是一维NumPy数组,而非字典,因此不能用solution['slope']或solution['intercept']这种键值对方式访问。同时,原工厂函数中传入的slope和intercept是固定初始值,并非GA需要优化的变量,违背了遗传算法优化参数的核心逻辑。

解决方案

  • 定义基因对应关系:将GA的num_genes设为2,数组第一个元素对应斜率(slope),第二个元素对应截距(intercept)。
  • 修正适应度函数:从solution数组中提取待优化的slope和intercept,计算预测值与真实值的误差,再转换为适应度值(添加极小值epsilon避免除零错误)。
  • 调整GA初始化参数:确保num_genes=2,其他参数按需设置。

修正后的完整代码

import numpy
import pygad

# 数据集:X是输入特征,Y是目标值
function_inputs = numpy.array([[1, 3, 5, 7], [2, 4, 6, 8]])

def fitness_function_factory(function_inputs):
    def fitness_function(solution, solution_idx):
        # 从solution数组中提取待优化的slope和intercept
        slope = solution[0]
        intercept = solution[1]
        
        # 计算预测值
        pred = slope * function_inputs[0] + intercept
        # 计算绝对误差之和
        error = numpy.sum(numpy.abs(pred - function_inputs[1]))
        # 添加epsilon避免除零错误
        fitness = 1.0 / (error + 1e-6)
        return fitness
    return fitness_function

# GA参数设置
num_generations = 100
num_parents_mating = 4
sol_per_pop = 8
num_genes = 2  # 对应slope和intercept两个待优化参数
init_range_low = -5
init_range_high = 5
parent_selection_type = "sss"
keep_parents = 1
crossover_type = "single_point"
mutation_type = "random"
mutation_percent_genes = 10

# 初始化GA并运行
lr_ga = pygad.GA(num_generations=num_generations,
                 num_parents_mating=num_parents_mating,
                 fitness_func=fitness_function_factory(function_inputs),
                 sol_per_pop=sol_per_pop,
                 num_genes=num_genes,
                 init_range_low=init_range_low,
                 init_range_high=init_range_high,
                 parent_selection_type=parent_selection_type,
                 keep_parents=keep_parents,
                 crossover_type=crossover_type,
                 mutation_type=mutation_type,
                 mutation_percent_genes=mutation_percent_genes)

lr_ga.run()

# 输出最优解
solution, solution_fitness, solution_idx = lr_ga.best_solution()
print(f"最优斜率: {solution[0]}, 最优截距: {solution[1]}")
print(f"最优适应度值: {solution_fitness}")

关键说明

  • 遗传算法会不断优化solution数组的两个元素,直到适应度值最大(即误差最小)。
  • 添加1e-6是为了防止误差为0时出现除以0的错误。
  • 运行结束后,通过best_solution()方法可直接获取最优的slope和intercept参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:15:36