[PYTHON] Find the optimal value of a function with a genetic algorithm (Part 2)

Last time

Code created last time https://qiita.com/nmat0031785/items/ceea6f78ab71e9956fce

Recording of optimization results

The previously used algorithms.eaSimple can only leave statistics for each generation. Improve so that the design variables and fitness of all individuals can be retained.

Generation and evaluation of initial population

First, the fitness is calculated only for the initial individual. After that, the design variable, fitness, generation (0 because it is the initial generation), and individual number are saved in pd.DataFrame.

sample_GA.py


#Generate an early population
pop = toolbox.population_guess()

#Evaluation of fitness of early individuals
fitnesses = toolbox.map(toolbox.evaluate, pop)
for ind, fit in zip(pop, fitnesses):
    ind.fitness.values = fit
fits = [ind.fitness.values[0] for ind in pop]

#Store initial individuals in logbook
logbook = pd.DataFrame([])
t1 = pd.DataFrame(pop)
t1.columns = ["x1", "x2"]
t1 = t1.assign(fits=fits, generation=0, ids=range(len(pop)))
logbook = logbook.append(t1)

Evolution loop

Enter the evolution loop. With offspring = toolbox.select (pop, POP_SIZE) , the individuals for POP_SIZE``` are reselected from the initial population pop```. This makes it possible to change the number of initial populations and evolutionary loop populations. Random numbers are given to individuals of each generation by for minutes, and individuals caught in `` CX_PB and `` `MUT_PB are crossed and targeted for mutation. After that, the fitness is re-evaluated for the new individual and added to pd.DataFrame.

sample_GA.py


#Parameters
N_GEN = 20       #Number of repeating generations
POP_SIZE = 100   #Population in the population
CX_PB = 0.8      #Crossing probability
MUT_PB = 0.05    #Mutation probability

#Evolution loop start
g = 0
while g < N_GEN:
    g = g + 1
    
    #Selection and replication of next-generation individuals
    offspring = toolbox.select(pop, POP_SIZE)
    offspring = list(map(toolbox.clone, offspring))

    #Crossing
    for child1, child2 in zip(offspring[::2], offspring[1::2]):
        #Select individuals to cross
        if random.random() < CX_PB:
            toolbox.mate(child1, child2)
            #Crossed individuals remove fitness
            del child1.fitness.values
            del child2.fitness.values

    #Mutation
    for mutant in offspring:
        #Select an individual to mutate
        if random.random() < MUT_PB:
            toolbox.mutate(mutant)
            #Mutant individuals remove fitness
            del mutant.fitness.values

    #Reassess the fitness of individuals whose fitness has been removed
    invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
    fitnesses = map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit
    
    #Update population with new generation population
    pop[:] = offspring

    #Extraction of fitness of all new generation individuals
    fits = [ind.fitness.values[0] for ind in pop]

    #Store in logbook
    t1 = pd.DataFrame(pop)
    t1.columns = ["x1", "x2"]
    t1 = t1.assign(fits=fits, generation=g, ids=range(POP_SIZE))
    logbook = logbook.append(t1)
    
    #debug
    print(t1)

terminal


・
・
・
-- Generation 20 --
          x1        x2        fits  generation  ids
0  -1.582142 -3.130247 -106.764537          20    0
1  -1.582142 -3.130247 -106.764537          20    1
2  -1.582142 -3.130247 -106.764537          20    2
3  -1.582142 -3.130247 -106.764537          20    3
4  -1.582142 -3.130247 -106.764537          20    4
..       ...       ...         ...         ...  ...
95 -1.582142 -3.130247 -106.764537          20   95
96 -1.582142 -3.130247 -106.764537          20   96
97 -1.582142 -3.130247 -106.764537          20   97
98 -1.582142 -3.130247 -106.764537          20   98
99 -1.582142 -3.130247 -106.764537          20   99

[100 rows x 5 columns]

Save

Save the result as CSV.

sample_GA.py


logbook.to_csv("result.csv", sep=",", index=None, header=None)

Summary

Output of design variables and fitness of each individual. Next time until the visualization of the results.

Recommended Posts

Find the optimal value of a function with a genetic algorithm (Part 2)
Finding the optimum value of a function using a genetic algorithm (Part 1)
Find the minimum value of a function by particle swarm optimization (PSO)
Finding a solution to the N-Queen problem with a genetic algorithm (2)
Find the index of the maximum value (minimum value) of a multidimensional array
Finding a solution to the N-Queen problem with a genetic algorithm (1)
The value of meta when specifying a function with no return value in Dask dataframe apply
Find the transfer function of one degree of freedom system with PythonControl.
If you give a list with the default argument of the function ...
How to find the memory address of a Pandas dataframe value
Count the maximum concatenated part of a random graph with NetworkX
[Python] A simple function to find the center coordinates of a circle
Compute the partition function with the sum-product algorithm
Find the SHA256 value with R (with bonus)
Search the maze with the python A * algorithm
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
How to fix the initial population with a genetic algorithm using DEAP
Tweet the weather forecast with a bot Part 2
Find the mood value with python (Rike Koi)
Find a position above the threshold with NumPy
Get the caller of a function in Python
Find the number of days in a month
Find the divisor of the value entered in python
Find out the day of the week with datetime
Visualize the behavior of the sorting algorithm with matplotlib
Find the shortest path with the Python Dijkstra's algorithm
Sequential calculation of mean value with online algorithm
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to solve the traveling salesman problem with a genetic algorithm (execution result)
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
To output a value even in the middle of a cell with Jupyter Notebook
[Verification] Try to align the point cloud with the optimization function of pytorch Part 1
Draw a graph with PyQtGraph Part 5-Increase the Y-axis
Various methods to numerically create the inverse function of a certain function Part 1 Polynomial regression
Find the sum of unique values with pandas crosstab
Get the value of a specific key in a list from the dictionary type in the list with Python
Cut a part of the string using a Python slice
Take a screenshot of the LCD with Python-LEGO Mindstorms
# Function that returns the character code of a string
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
Find out the location of packages installed with pip
Visualize the characteristic vocabulary of a document with D3.js
Tweet the probability of precipitation as part of the function of the bot
[Python & SQLite] I analyzed the expected value of a race with horses with a win of 1x ②
Notification of weather forecast (rain, etc.) by DM as a part of the function of bot
Calculate the product of matrices with a character expression?
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
I tried to find the entropy of the image with python
Find out the apparent width of a string in python
A network diagram was created with the data of COVID-19.
I tried to find the average of the sequence with TensorFlow
Measure the importance of features with a random forest tool
Get the id of a GPU with low memory usage
Get UNIXTIME at the beginning of today with a command
Inherit the standard library to find the average value of Queue
[Python] Try optimizing FX systole parameters with a genetic algorithm
Your URL didn't respond with the value of the challenge parameter.
Check the scope of local variables with the Python locals function.
I made a function to check the model of DCGAN