Python Genetic Algorithm by using PyGAD library

Viewed 44

I have a function that I want to maximize its value.

But I don't know much how to use PyGad library. What I see on some sites is that they always use default functions like w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6. Where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7). And there they write the code without write the function just like :

function_inputs = [4,-2,3.5,5,-11,-4.7]  # Function inputs.
desired_output = 44  # Function output.

And add the other parameters

So what if we want to use a polynomial function like w1^3.x1 + w2^2.x2 + w3.x3 + w4.x4 + w5.x5 + w6.x6?

1 Answers

It is simple. Just write your function in Python.

(w1**3)*(x1) + (w2**2)*(x2) + (w3)*(x3) + (w4)*(x4) + (w5)*(x5) + (w6)*(x6)

For the complete example, please use the next fitness function instead of the function used in this example.

def fitness_func(solution, solution_idx):
    w1, w2, w3, w4, w5, w6 = solution
    x1, x2, x3, x4, x5, x6 = function_inputs
    output = (w1**3)*(x1) + (w2**2)*(x2) + (w3)*(x3) + (w4)*(x4) + (w5)*(x5) + (w6)*(x6)
    fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
    return fitness

Thanks for using PyGAD!

Related