Using genetic algorithm function extremum (fortran)

EDITORIAL

This article suitable for some emergency learn Friends optimization algorithm, for Gangster level students please skip, after all, only a small series and has little to traditional computer engineering students.

Xiao Bian first encounter the genetic algorithm is a US junior season, when the need to learn some optimization algorithms. However, as the ancient level of genetic algorithm optimization algorithm is a natural target my first learning.

Write how I feel about the GA, this algorithm is intelligent algorithm is theoretically possible to achieve the global optimum but after a period of learning, feeling for some complex functions really want to achieve the global optimum need some luck. This algorithm is the most classic of late have appeared many similar algorithms, particle swarm optimization, ant colony algorithm and the like. Here do evaluation, Xiao Bian feel like learning one, a pass Belden thing.

Finally ! ! ! ! ! This time I used the GA is complete computing some complex functions. Here are some key steps and some tips to protect yourself from back late review. (Ps complete Code Available passed up late)

Past and Present Genetic Algorithm

The concept was first used by the genetic algorithm Bagley JD
presented in 1967. Later JHHolland professor at the University of Michigan began genetic algorithm (Genetic Algorithm, in 1975
the mechanism GA) conducted systematic research. Genetic algorithm is a simple simulation of the Darwinian theory of biological evolution, following a "survival of the fittest", "slightly better elimination" principle. Genetic algorithm simulates a population of artificial evolution, and through the mechanism of selection, hybridization and mutation, populations over several generations later, is always optimal (or near optimal) state.

Since genetic algorithms have been proposed, it has been widely used, especially in function optimization, production scheduling, pattern recognition, neural networks, adaptive control and other fields, the genetic algorithm is playing a major role greatly improve the problem solving s efficiency. Genetic algorithm is an important research topic in the field of the current "soft computing."

Firstly fortran combination of genetic algorithm process for detailed analysis, and then by an actual function optimization case their applications are discussed.

Algorithm steps Introduction

Many people have already written a few basic steps genetic algorithm, I'm not elaborated here, directly to the address down, you can go to thin products. This algorithm is that so amazing.

https://blog.csdn.net/qq_34374664/article/details/78874956

Before a lot of my inspiration blog not find it, but after reading his article, I believe the general process you will have an understanding of GA

I remember reading come back to see me the next show Oh!

Ha ha ha ha ha, is not that is so amazing, how strong do not need the ability to understand mathematics can understand.

The main structure of the genetic algorithm

Let's start with genetic algorithm programming links
First, we need to sort out ideas to think about the whole process needed to calculate where several functions (subroutine)
1. population initialization
2. Calculate the fitness of the population
3. Population fitness sorting
4. Select (screening) operation
5. crossover
6. mutation
function used above is required.
Secondly, we need to have some awareness compile large programs. For some data variables can be set globally and has been preserved, so we need to put some amount in advance frequently used rationale for it.
pop_size: Enter the population size
chromo_size: Enter the length of the chromosome
generation_size: Enter the number of iterations
cross_rate: Enter the crossover probability
cross_rate: Enter the mutation probability
elitism: input is elitist selection
(these variables when used back then explain)

Begin to solve:

1. Population Initialization:

integer i,j,k
integer pop_size, chromo_size,pop_num
real x
call RANDOM_SEED()
do i=1,pop_size
    do j=1,pop_num
    do k=1,chromo_size
        call RANDOM_NUMBER(x)
        pop(i,j,k) = nint(x)
    end do
    end do
end do

Language interpretation: for each individual size of the pop-size population, the individual dimensions of the pop-num, on the size of the length of chromosome chromo_size random assignment of each dimension.
Generation function () __ a substantially random number RANDOM_SEED

2. Calculate the fitness of individual populations (of different optimization goals, here need to rewrite)

 integer i,j,k
    integer pop_size,pop_num,chromo_size
    real fitness_value1(pop_size,pop_num).
    
!do  i=1,pop_size(单层维度,一个自变量时的初始化方法)
!   fitness_value(i) = 0.  
!end do

do i=1,pop_size
   do j=1,pop_num
       do k=1,chromo_size
      if (pop(i,j,k) == 1)then
            fitness_value1(i,j) = fitness_value1(i,j)+2**(k-1)
      end if
      
   end  do     
   fitness_value1(i,j) = -500+fitness_value1(i,j)*(500-(-500))/(2**chromo_size-1)
     
     fitness_value1(i,j) = fitness_value1(i,j)*sin(sqrt(fitness_value1(i,j)))      !*****   *********更改函数
     
     fitness_value(i)=fitness_value1(i,j)+fitness_value(i)
end do

end do

3. Population sort
of individual fitness sorted by size, and save the best individual

integer pop_size,pop_num,chromo_size
integer i,j,k,m,min,temp
integer temp1(pop_num,chromo_size)

do  i=1,pop_size    
    fitness_table(i) = 0.
end do

min = 1
temp = 1
temp1(pop_num,chromo_size)=0
 do  i=1,pop_size
    min = i
   do j = i+1,pop_size
if (fitness_value(j)<fitness_value(min))then
            min = j
end if
end do
if (min/=i)then
        temp = fitness_value(i)
        fitness_value(i) = fitness_value(min)
        fitness_value(min) = temp
do m=1,pop_num
   do k = 1,chromo_size
            temp1(m,k) = pop(i,m,k)
            pop(i,m,k) = pop(min,m,k)
            pop(min,m,k) = temp1(m,k)
   end do
end do

end if

end do

do i=1,pop_size
if (i==1)then
        fitness_table(i) = fitness_table(i) + fitness_value(i)   
else
        fitness_table(i) = fitness_table(i-1) + fitness_value(i)
end if
end do
!fitness_table!***********************????????????????
fitness_avg(G) = fitness_table(pop_size)/pop_size


if (fitness_value(pop_size) > best_fitness)then
    best_fitness = fitness_value(pop_size)
    best_generation = G
end if
do i=1,pop_num
do  j=1,chromo_size
        best_individual(i,j) = pop(pop_size,i,j)
end do
end do

4. Roulette selection operation
required for processing the population disadvantages for different population distribution "Function mountain" on. Rule processing is the use of the fitness function of the size calculated in the third step as a population size of each distribution angle on the wheel.
Then turn the wheel, select who, and anyone can survive. Which obviously can be obtained: For low fitness of the smallest populations most likely to be chosen.
If luck is extremely poor, resulting in excellent population are excluded, we can take "walks" approach to these outstanding stocks. ( This refers to such attention is needed in the way walks in moderation, prevent local optimization )

integer pop_size, chromo_size,elitism,pop_num
integer i,j,k,p,r,mid,first,last,idx
real x,w,q

call RANDOM_SEED()
call RANDOM_NUMBER(x)
do i=1,pop_size
    r = x * fitness_table(pop_size)
    first = 1
    last = pop_size
    w=(last+first)/2
    mid = nint(w)
    idx = -1
do while ((first <= last).and.(idx == -1) )
  if (r > fitness_table(mid))then
            first = mid
else if (r < fitness_table(mid))then
            last = mid  
else
            idx = mid
exit
end if
q=(last+first)/2
        mid = nint(q)
   if ((last - first) == 1)then
            idx = last
   exit
  end if
end do
do k=1,pop_num
    do j=1,chromo_size
        pop_new(i,k,j)=pop(idx,k,j)
    end do
end do
end do

!**************************保送选择*************************
if (elitism==1)then
    p = pop_size-1
else
    p = pop_size
end if
do  i=1,p
    do k=1,pop_num
    do  j=1,chromo_size
        pop(i,k,j) = pop_new(i,k,j)
    end do
end do
end do

The single-point crossover

implicit none
integer pop_size, chromo_size,cross_rate,pop_num
integer i,j,k,cross_pos,temp
real x

call RANDOM_SEED()
do i=1,pop_size,2
    do k=1,pop_num
    call RANDOM_NUMBER(x)
    if(x < cross_rate)then
        cross_pos = nint(x * chromo_size)    !交叉位置
       if(cross_pos == 0.or.cross_pos == 1)then
         cycle
       end if
       
     do  j=cross_pos,chromo_size
            temp = pop(i,k,j)
            pop(i,k,j) = pop(i+1,k,j)
            pop(i+1,k,j) = temp
     end do

end if
    end do
end do

6. mutation

!pop_size: 种群大小
!chromo_size: 染色体长度
!cross_rate: 变异概率
subroutine mutation(pop_size, chromo_size, mutate_rate,pop_num)
use a10
implicit none
integer i,j,mutate_pos
real x
integer pop_size, chromo_size,mutate_rate,pop_num
call RANDOM_SEED()
 do i=1,pop_size
     do j=1,pop_num
    call RANDOM_NUMBER(x)
    if (x < mutate_rate)then
        mutate_pos = nint(x*chromo_size)
        if (mutate_pos == 0)then
        cycle
        end if
        pop(i,j,mutate_pos) = 1 - pop(i,j, mutate_pos)
    end if
    
     end do
 end do

Mutation and crossover operation is similar, but its effects are different sizes. Cross operation is equivalent to the population is a function of friendship between the mountains to expand the territory between them, their position clear in the middle of the blind spot. He is relatively controllable. In contrast mutation, it is the random beating, the population may go better place to go, it could go worse places. This requires the reader to modify the parameters to obtain optimal results.
At this point, the solution process is completed

The results show that:

Here the original function yes. . . . . Reference fitness calculation where the line changes function, a thirty-dimension function.
Here is the main program:

program GA
use a10
implicit none
!real,external :: fitness***********还是用子程序好用
!integer,external:: rank
!real,external ::selection
!real,external :: crossover
!real,external :: mutation

integer m(30,24),p,j,i
real n,q(30)
integer,save::pop_size        !种群大小
integer ,save::pop_num        !单个种群维度
integer,save::chromo_size     !染色体大小**********                                      *********更改
integer ,save::elitism        !选择精英操作
integer ,save::cross_rate       !交叉概率
integer ,save::mutate_rate     !变异概率

!function [m,n,p,q] = GeneticAlgorithm(pop_size, chromo_size, generation_size, cross_rate, mutate_rate, elitism)
elitism = 1             !选择精英操作
pop_size = 1000           !种群大小
pop_num=30              !维度30
chromo_size = 24       !染色体大小
generation_size = 200   !迭代次数
cross_rate = 0.5        !交叉概率
mutate_rate = 0.01      !变异概率

  
!print *, '开始了'
  
  
fitness_avg = 0.


fitness_value(pop_size) = 0.
best_fitness = 0.
best_generation = 0

call initilize(pop_size,pop_num,chromo_size)          !初始化

do  G=1,generation_size   
  call fitness(pop_size,pop_num,chromo_size)                !计算适应度 
  call  rank(pop_size,pop_num,chromo_size)                  !对个体按适应度大小进行排序
  call selection(pop_size, chromo_size,elitism,pop_num)      !选择操作
  call crossover(pop_size, chromo_size, cross_rate,pop_num)  !交叉操作
  call mutation(pop_size, chromo_size, mutate_rate,pop_num)  !变异操作
end do


!****                                               ******************matlab中打印图像****************


m = best_individual                   !获得最佳个体
n = best_fitness                 !获得最佳适应度
p = best_generation                   !获得最佳个体出现代

!获得最佳个体变量值,对不同的优化目标,此处需要改写
q = 0.
do i=1,pop_num
do j=1,chromo_size
    if (best_individual(i,j) == 1)then
          q(i)= q(i)+2**(j-1)
    end  if
end do




!!!!!!!!!!!!!!!!!*********************************更改为对应的自变量的值**********************
                            q(i) = -500+q(i)*(500-(-500))/(2**chromo_size-1)
end do





write(*,*)"最优个体"
write(*,*) m
write(*,*)"最优适应度"
write(*,*) n
write(*,*)"最优个体自变量"
write(*,*) q
write(*,*)"最优代数"
write(*,*) p

end program GA

Because the function does not calculate a lot of time to save the most original one, in the middle may be a bit do not correspond. But the general idea have shown the

Finally, place it should be noted that some of

  1. You need to understand the conversion between binary and decimal. Here is the use of interpolation techniques.
  2. We need to know to write large programs fortran modular in order to invoke the data.

Finally it, time is limited, small series lazy, free again to add. In order to review after yourself.
Xiao Bian is a graduate of hydraulic structures, if you read this, we can more exchanges.

Published an original article · won praise 0 · Views 58

Guess you like

Origin blog.csdn.net/lameta/article/details/102652779