Is there something wrong with my crossover function?

Viewed 61

I am coding differential evolution on python and I sometimes(very rarely) get the error of too many recursive calls. I want to improve on coding functions so thought this was a good place to ask.

I initialize a mutant vector in another function and then generate a trial vector by entering the relevant parameters. random_select basically just picks a random vector from my population of candidates(here called vectors) vector is a candidate in the population. H and K are the hyperparameters I decided to use for my optimization problem.

Here is my code: (numpy as np and numpy.random as npr)

def random_select(arr: np.array, size: int = 1):
    return arr[np.random.choice(len(arr), size=size, replace=False)]

def generate_Mutant(vector, K, F, vectors):
    Xr1 = random_select(vectors)[0]
    Xr2 = random_select(vectors)[0]
    Xr3 = random_select(vectors)[0]
    return vector + K*(Xr1 - vector) + F*(Xr2 - Xr3)


def Crossover(Crossover_probability, mutant, vector, K, F, vectors, boundaries):
    trial = []
    for item in range(len(mutant)):
        if npr.random_sample() > Crossover_probability:
            trial.append(mutant[item])
        else:
            trial.append(vector[item])
    flag = 0
    for index in range(len(trial)):
        if trial[index] > boundaries[index][0] or trial[index] < boundaries[index][1]:
            flag = 1
            mutant = generate_Mutant(vector, K, F, vectors)
            return Crossover(Crossover_probability, mutant, vector, K, F, vectors, boundaries)
    if flag == 0:
        return np.array(trial)

Is there any way I can improve this function? Some function or library I missed that allows me to do this even better? Some way of coding which is much better than the one I currently use? Anything helps, I just want an opinion.

0 Answers
Related