SoFunction
Updated on 2024-10-30

Code for implementing python genetic algorithm to find the extreme value of a function

Without further ado, let's just look at the code!

"""Genetic Algorithm Implementation for Function Maximization-Zjh"""
import numpy as np
import random
import  as plt
class Ga():
 """Find the length of the binary code."""
 def __init__(self):
   = -2
   = 3
  precision = 0.0001 # Operational accuracy
   = int(np.log2(( - )/precision))+1#% Chromosome length
   = 50# Initial population size
   = 12# Maximum number of evolutionary generations
   = 0.90# Cross probabilities
   = 0.2# Probability of variation
  =(0,2,size=(,))
 
 """Calculating Adaptation."""
 def fitness(self,population):
  Fitvalue=[]
  cumsump = []
  for i in population:
   x=self.transform2to10(i)# Decimal equivalent of binary
   xx= + x * ( - ) / (pow(2,)-1)
   s=(xx)
   (s)
  fsum=sum(Fitvalue)
  everypopulation=[x/fsum for x in Fitvalue]
  (everypopulation[0])
  (everypopulation[0])
  for j in everypopulation:
   p=cumsump[-1]+j
   (p)
  return Fitvalue,cumsump
 """Select two genes and prepare for crossover."""
 def select(self,cumsump):
  seln=[]
  for i in range(2):
   j = 1
   r=(0,1)
   prand =[x-r for x in cumsump]
   while prand[j] < 0:
    j = j + 1
   (j)
  return seln
 """Cross."""
 def crossover(self, seln, pc):
  d=[seln[1]].copy()
  f=[seln[0]].copy()
  r=()
  if r<pc:
   print('yes')
   c=(1,-1)
   print(c)
   a=[seln[1]][c:]
   b=[seln[0]][c:]
   d[c:]=b
   f[c:]=a
   print(d)
   print(f)
   g=d
   h=f
  else:
   g=[seln[1]]
   h=[seln[0]]
  return g,h
 """Mutant operation."""
 def mutation(self,scnew,pmutation):
  r=(0, 1)
  if r < pmutation:
   v=(0,)
   scnew[v]=abs(scnew[v]-1)
  else:
   scnew=scnew
  return scnew
 
 """Binary to decimal conversion."""
 def transform2to10(self,population):
  #x=population[-1] #value of the last digit
  x=0
  #n=len(population)
  n=
  p=()
  p=()
  ()
  for j in range(n):
   x=x+p[j]*pow(2,j)
  return x # Returns a decimal number
 """Objective function"""
 def targetfun(self,x):
  #y = x∗((10∗()∗x))+ 2
  y=x*((10**x))+2
  return y
 
if __name__ == '__main__':
 Generationmax=12
 gg=Ga()
 scnew=[]
 ymax=[]
 #print()
 Fitvalue, cumsump=()
 Generation = 1
 while Generation < Generationmax +1:
  Fitvalue, cumsump = ()
  for j in range(0,,2):
   seln = ( cumsump) # Returns the serial numbers of the 2 selected individuals
   scro = (seln, ) # Return two chromosomes
   s1=(scro[0],)
   s2=(scro[1],)
   (s1)
   (s2)
   = scnew
  Fitvalue, cumsump = ()
  fmax=max(Fitvalue)
  d=(fmax)
  (fmax)
  x = gg.transform2to10([d])
  xx =  + x * ( - ) / (pow(2, ) - 1)
  Generation = Generation + 1
 Bestpopulation = xx
 Targetmax = (xx)
 print(xx)
 print(Targetmax)
 
x=(-2,3,30)
y=x*((10**x))+2
(2.65,4.65,c='red')
(0,5)
(0,6)
(x,y)
('local max', xy=(2.7,4.8), xytext=(3.6, 5.2),arrowprops=dict(facecolor='black', shrink=0.05))
()

An assignment for a simulation of a function to find an extreme value, referenced someone else's matlab code and reproduced it in python to get a better impression!

Above this python genetic algorithm for function extreme value of the implementation of the code is all I share with you, I hope to be able to give you a reference, and I hope you support me more.