数学建模社区-数学中国

标题: 遗传算法(python版) [打印本页]

作者: 1440359316    时间: 2021-6-19 15:17
标题: 遗传算法(python版)
1.png
6 C5 h  w! K9 z3 N; S1 V, ]0 @遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。该法则很好地诠释了生物进化的自然选择过程。遗传算法也是借鉴该基本法则,通过基于种群的思想,将问题的解通过编码的方式转化为种群中的个体,并让这些个体不断地通过选择、交叉和变异算子模拟生物的进化过程,然后利用“优胜劣汰”法则选择种群中适应性较强的个体构成子种群,然后让子种群重复类似的进化过程,直到找到问题的最优解或者到达一定的进化(运算)时间。
+ F5 K, w7 W8 W2 O( N( S4 N/ `3 ]( p+ l* p$ \+ y
Ga算法中的几个重要名词概念。5 ~3 J; w* f% E! H% ~& }7 X

9 Z+ \- w( k& U9 Y个体(染色体):自然界中一个个体(染色体)代表一个生物,在GA算法中,个体(染色体)代表了具体问题的一个解。* x$ K" K# j& h
2.png + h5 R. r4 T9 e3 A3 N- Z/ t- `" F

" s; w) g) g( D7 h3 l7 Z基因:在GA算法中,基因代表了具体问题解的一个决策变量,问题解和染色体中基因的对应关系如下所示:
, u& N2 W. A) t* q6 p9 M
/ |* H: g, H% V( M8 ` 3.png
) r( W* W( `  S8 P6 G# i. g" ~种群:多个个体即组成一个种群。GA算法中,一个问题的多组解即构成了问题的解的种群。+ i0 @9 w6 M0 O4 z& ?) W

# c8 U; c3 g' @" x7 ?2、主要步骤4 N. v5 K8 T" _  G
GA算法的基本步骤如下:
7 S9 z4 Q0 n$ F! U. }( Q1 y# a) E, Q9 u
Step 1. 种群初始化。选择一种编码方案然后在解空间内通过随机生成的方式初始化一定数量的个体构成GA的种群。; ^) F) @+ j# N( N9 w0 }9 @

) F% C' K/ E& t* f9 p+ jStep 2. 评估种群。利用启发式算法对种群中的个体(矩形件的排入顺序)生成排样图并依此计算个体的适应函数值(利用率),然后保存当前种群中的最优个体作为搜索到的最优解。
% w9 {5 S; \5 i5 x! z1 k1 x, n  c, i$ }& Z" u# L
Step 3. 选择操作。根据种群中个体的适应度的大小,通过轮盘赌或者期望值方法,将适应度高的个体从当前种群中选择出来。6 s; `6 r+ f- b1 I( ]

8 {2 j1 {% m2 j0 vStep 4. 交叉操作。将上一步骤选择的个体,用一定的概率阀值Pc控制是否利用单点交叉、多点交叉或者其他交叉方式生成新的交叉个体。
3 s1 U/ x, ~5 e" e7 n$ Z& f0 N4 f6 `/ r+ j! Q5 ?. G
Step 5. 变异操作。用一定的概率阀值Pm控制是否对个体的部分基因执行单点变异或多点变异。
& m- h% C" s3 N  S# j8 a/ O
9 w$ T3 L) [9 F. jStep 6. 终止判断。若满足终止条件,则终止算法,否则返回Step 2。
7 \+ e% O! H2 _* S5 |
. G* l+ G/ i( k# i- r* ~( d6 k" u4 ?流程图如下所示:0 i+ U/ G- y$ i
4.png
* T0 q/ p& E- H$ B3 U7 |7 {. L2 K9 \0 j( C& |/ e
3、主要操作介绍& X* Y- s/ ?. g' p, T/ Y
3.1 种群初始化4 ]  u7 C0 U* c: @, T; q! ?
种群的初始化和具体的问题有关。比如一个问题有n个决策变量{x1,x2,…,xn}。每个决策变量有取值范围:下界{L1,L2,…,Ln}和上界{U1,U2,…,Un},则种群中个体的初始化即随机地在决策变量的取值范围内生成各个决策变量的值:Xj={x1,x2,...,xn},其中xi属于范围(Li,Ui)内。所有的个体即构成种群。当每个个体都初始化后,即种群完成初始化。  N1 w  q& o* X6 u# J: W  q! }
$ ?& g9 T4 B; O0 W% C( [
3.2 评价种群
/ g+ s, T3 K8 S4 ?1 P种群的评价即计算种群中个体的适应度值。假设种群population有popsize个个体。依次计算每个个体的适应度值及评价种群。* P# I$ Y- y  [/ n+ `% \
" c+ K5 A! e- {- A) h+ ]6 @( _
3.3 选择操作2 n' E' A! M9 W/ ?( m" t' \9 l
GA算法中常见的选择操作有轮盘赌方式:种群中适应度值更优的个体被选择的概率越大。假设popsize=4,按照如下表达式计算各个个体的被选择概率的大小,然后用圆饼图表示如下。
, b" p2 p5 Y! F) t6 ~8 Y
  q% m2 i. I  g3 g; x8 x' U: B* LP(Xj) = fit(Xj)/(fit(X1)+fit(X2)+fit(X3)+fit(X4)),j=1,2,3,4
/ u4 R* v- a  p5 ~! p! m 5.png
! J7 i3 g& r( o" S: l* n* R
0 K- k$ H2 I% Z+ f* Y3 O+ _1 b当依据轮盘赌方式进行选择时,则概率越大的越容易被选择到。, v7 k1 e) y4 ^: s

+ T; E0 u" h* n2 r1 q1 j3.4 交叉操作, T5 [0 ~* `: s: |1 v
交叉操作也有许多种:单点交叉,两点交叉等。此处仅讲解一下两点交叉。首先利用选择操作从种群中选择两个父辈个体parent1和parent2,然后随机产生两个位置pos1和pos2,将这两个位置中间的基因位信息进行交换,便得到下图所示的off1和off2两个个体,但是这两个个体中一般会存在基因位信息冲突的现象(整数编码时),此时需要对off1和off2个体进行调整:off1中的冲突基因根据parent1中的基因调整为parent2中的相同位置处的基因。如off1中的“1”出现了两次,则第二处的“1”需要调整为parent1中“1”对应的parent2中的“4”,依次类推处理off1中的相冲突的基因。需要注意的是,调整off2,则需要参考parent2。" t  G0 i4 A  J: X
4 m3 H0 C, s1 b  }( [; l
6.png ( f; r' _7 ^; h/ v5 w7 M

3 R. o4 _9 Z/ ^' g9 W3.5 变异操作
" C2 S; g2 V1 W变异操作的话,根据不同的编码方式有不同的变异操作。
# Y# A. D0 P9 v
6 U5 h; A2 L) l7 n, Q: o0 b' k! C如果是浮点数编码,则变异可以就染色体中间的某一个基因位的信息进行变异(重新生成或者其他调整方案)。
7 T, g2 P# @! v7 }9 i4 o- n; M( b
+ J( N+ R" [( \: q& a. I 7.png # m7 ~  U  }( L/ U
如果是采用整数编码方案,则一般有多种变异方法:位置变异和符号变异。
1 A0 S% V, p. A& z$ W$ u3 [8 w! ?# F* p! {! `7 x$ O2 K" y2 b
位置变异: ) d$ T' X8 c% y# L; S$ T
8.png
* r* F4 E) f8 ]) H2 g% y$ H- b) i$ [8 S6 u$ N  t
符号变异:   [% w( o+ p; \
9.png
; H* ?2 J1 q' G
4 U+ @  e/ p2 ^! M: ?4 t4、Python代码
  K% B) R0 D* O7 J& Z3 A! T#-*- coding:utf-8 -*-" o/ a0 _; u6 E9 h) o
0 W& `( p* i! ~" V; `
import random
" ^2 h" L% ?# @import math
' w% C  T2 w; b  \from operator import itemgetter$ ]: u( e$ U1 Q+ h: z+ s
3 O5 P$ b) z6 G
class Gene:  A, Y$ v2 j+ W/ g
    '''( M2 A/ F6 K$ B0 I
    This is a class to represent individual(Gene) in GA algorithom
, `  \# ?8 C. G1 b, ]    each object of this class have two attribute: data, size
) w/ n( `7 {/ ?# C    '''8 V  J5 ]# ?' m7 t) p
    def __init__(self,**data):4 r9 q' t# T! j& B: V, L* f; c
        self.__dict__.update(data)       ! |. z+ N9 _! }* l0 i
        self.size = len(data['data'])#length of gene2 o" g7 b  t: l5 m1 A

3 R6 L* p2 a! P/ m& ?. Y7 f6 P( h
class GA:
8 S* y! @9 @2 u$ D$ C    '''
& I- h. _. Z- p# U' `    This is a class of GA algorithm. , t" H+ k( a# I. Z6 ^
    '''# h1 R) @0 s, n7 B% V" T
    def __init__(self,parameter):
# t& T0 ^, y% o* A        '''  B3 i# ~% ]3 Q& n+ r
        Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .. F0 }# W5 A. q
        The data structure of pop is composed of several individuals which has the form like that:5 T' U' m! t! v, `

- R7 D3 _! k4 {7 Y# |4 k6 G        {'Gene':a object of class Gene, 'fitness': 1.02(for example)}2 a0 Q" @% U. f6 w5 v9 {
        Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]
  C7 |5 G: |1 Q9 X3 D$ q: g' x& F. q( _2 O  y1 I+ a* a
        '''
$ f1 q0 i6 |- f- X3 {        #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]; P: v; S' J! M4 S1 v% ]5 k4 r
        self.parameter = parameter  }% B1 n- @, W8 r% y
7 x" K( R: W9 X
        low = self.parameter[4]9 `7 m* ~* L# f+ D( [' Q" b2 M1 O
        up = self.parameter[5]- h/ V& N( @% {- K6 G% a. M% Z' R
9 M: j! Y6 t& R2 r: d5 Y
        self.bound = []- B  o4 D- y/ R. |) {
        self.bound.append(low)( ]$ v) q- P/ N% C* i+ s1 @
        self.bound.append(up)# `1 w: D) T- y: n
) E# x# p; `) ?
        pop = []: g6 ~4 J! l2 o. N
        for i in range(self.parameter[3]):
/ N$ m& ?" ]! K: d& ?            geneinfo = []
" Y. H( a/ B) H0 X: `$ R, M  S8 r) m            for pos in range(len(low)):3 {; c2 m8 [. f$ u2 [: R. z( Y
                geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation
* _* r; ~2 T; i$ [7 a) K, ]3 s  _, M% N) V
            fitness = evaluate(geneinfo)#evaluate each chromosome
) k- W2 q& J/ s6 f            pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness+ K! K1 \. u  J$ Z, A; ~+ ^
; x) L" V' `- C3 W
        self.pop = pop' E/ a* s+ f% g
        self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population
1 ^* O* c: j3 Z3 l& t& S
: A, }' M, _2 J    def selectBest(self, pop):
% `3 n% ?- |1 l+ q  e        '''
" E/ g* E7 P$ o/ V: K3 d* Y- A        select the best individual from pop& R. i. i+ y+ H. G
        '''2 D% l+ ]7 L! h3 [
        s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)% K* t% Z' v% M/ ]8 ]
        return s_inds[0]( Y( |0 ~' D( C  f8 F
6 Z, j6 e7 g& A/ D( B2 U
    def selection(self, individuals, k):3 T7 \9 }* h0 }" T2 o0 q
        '''5 ~9 f: @) T- H6 L" S
        select two individuals from pop
; j% a' _/ N' r0 o        '''
3 O$ Q1 H$ K- K% ]) @% @, U        s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness + H5 U) g* G; U
        sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop  |* v. I+ _) R& d6 J$ V; q. r
$ a0 Q4 h% w. c2 p8 i  b
        chosen = []2 W0 D! Z3 [3 P9 h% N
        for i in xrange(k):5 w  ]* x/ t, t& y5 b
            u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]/ N1 m( H; I! N: M) F( L/ y, i: a
            sum_ = 0% p: c( u) x+ |1 i  x8 U7 t1 l
            for ind in s_inds:( C1 \- r+ O7 a; t
                sum_ += 1/ind['fitness']#sum up the 1/fitness8 i( U& @  r* X9 |" _  F; b
                if sum_ > u:$ G( ~3 J! M( n( j2 t( Y/ l% {
                    #when the sum of 1/fitness is bigger than u, choose the one, which means u is in the range of [sum(1,2,...,n-1),sum(1,2,...,n)] and is time to choose the one ,namely n-th individual in the pop: v5 |' I( d" }  x( f
                    chosen.append(ind)
2 B$ g$ R# y  N5 U3 ^- R                    break
4 b; J" M9 P, a5 m* y* F  y+ F, e! q
        return chosen   
  D2 s9 ~- X4 [0 S1 P" L5 U6 t& s6 s2 t% b

) f) D! p7 j+ h    def crossoperate(self, offspring):* ]: `8 A" p3 q# E  b$ q
        '''
! E8 _8 J+ p6 Y+ l! F# _! b* X        cross operation  b6 P2 g3 t  L' T' g$ o' y
        '''
3 H7 `+ Y; v# R7 [        dim = len(offspring[0]['Gene'].data)
, i7 `) |' u% b2 H$ m' C, w' j5 \0 X. P! A% i8 W  W& s1 x
        geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop5 E; T: Z5 E& y$ y+ v# e% Y( `2 r
        geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop( ^* R, E1 u  m3 c

+ L! a; I: W: A& b2 w6 l  P- f( f5 Z        pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1,   E) A6 V7 M* c% q8 j
        pos2 = random.randrange(1,dim)- `: x( i( C2 y. C! p

5 w' O2 l% [+ c9 z        newoff = Gene(data = [])#offspring produced by cross operation# R" ^" l2 x% a2 `, w' z7 G3 C2 d; P
        temp = []. s# [3 h3 \7 M7 Z7 `
        for i in range(dim):$ ^( Q) H+ r, o4 q, ]& M
            if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):8 J4 f' i, g* @6 N
                temp.append(geninfo2)% X$ R, N7 }! |; c9 j" U$ L& [4 f& O3 Y
                #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)]9 [  U; e* _$ `" @5 K1 h6 g
            else:9 R5 k9 z( ^: W+ I7 m
                temp.append(geninfo1)0 ]5 t, ^, P$ _0 g, Q- W6 G  @
                #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]/ v, L3 m# u& z7 m/ ]! W0 }! i
        newoff.data = temp
& t: z8 m8 J4 b6 V& J  t) [4 ?& C/ V1 v/ p" z% C
        return newoff
5 ]3 [8 m3 h# J4 L+ ]4 ^  p4 o4 E" ]# Q3 K8 p' ^! K6 H
, ~. J$ K& T7 o- f# w$ c$ S
    def mutation(self, crossoff, bound):( W2 ^" i; g* n- F5 ?
        '''
, O" m9 {8 h; O. R$ j        mutation operation4 S) ~3 F. f9 U# m8 s
        '''8 d. y! ]/ z; g$ j/ |, C
% K4 G$ \+ w* d8 I+ o
        dim = len(crossoff.data)
' T. P; P) ]5 C
* M7 H/ t, D( [  e% |- E" z: A' ~8 X        pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.
0 _' s5 u& O# q$ L! p
5 [. G: o9 N! i  Z0 |        crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])
% O; ?( I# `6 ]! S        return crossoff7 }8 N+ o/ ?$ s- Q5 [. v6 e) \
) w; Q* m! E+ y6 D8 ^
    def GA_main(self):# W: I7 P! L7 p4 O4 z. O  g- M
        '''
% h5 T- j6 U+ h8 T) i7 G; U( _7 n        main frame work of GA
. a) h) C5 s3 |; _9 f# [8 r% F/ E        '''/ S8 S( N+ j4 I: e5 L% T$ X
4 q6 T% L% m2 _6 B% s7 \+ I
        popsize = self.parameter[3]5 x- D) Q& S% X7 N4 I! N9 j5 F# `
. {0 t8 j+ n  u9 C8 o& F4 Z7 g
        print("Start of evolution")- ]0 Z5 L4 h( k) H- G: x  c' K2 |+ ~
( x* ~$ Q7 S& \% a8 \1 X+ m. P
        # Begin the evolution
+ @& L7 _/ z/ i/ B: a/ O        for g in range(NGEN):/ T2 V+ K& h( {) M5 y8 i

# Z% X$ s- {! ]3 R* x            print("-- Generation %i --" % g)      ; ?; |( `  o+ W+ M! B

$ Y. u9 h' N4 v% q" X, m            #Apply selection based on their converted fitness; R5 z* n' G# p
            selectpop = self.selection(self.pop, popsize)   
2 H2 r8 s1 V9 t2 W* }" q* ?/ d+ Q6 X" U
            nextoff = []    6 S: N- t9 U/ E* T! y8 e0 L
            while len(nextoff) != popsize:      
- n8 `8 q* G! U0 I/ H                # Apply crossover and mutation on the offspring            ) ^6 t$ M' h2 Q9 c  i
) q, B0 X) x; K: p8 V3 T) b4 c8 b
                # Select two individuals! k$ H3 H; P, T" \: D
                offspring = [random.choice(selectpop) for i in xrange(2)]6 I6 D; ?# H- T
7 k- V+ F1 x( j
                if random.random() < CXPB: # cross two individuals with probability CXPB
" d& q& a; V4 \. y, e0 Z. Y                    crossoff = self.crossoperate(offspring)) {! K% E7 o5 i/ b! E
                    fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals           
/ M7 ]0 h& b  v; A6 @$ h# N% m; @  j8 v& Y: O" x( u
                    if random.random() < MUTPB: # mutate an individual with probability MUTPB: A* M3 a, I* v2 Y6 v. B
                        muteoff = self.mutation(crossoff,self.bound)0 L% o* R# d$ U& a: W
                        fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals
# m* I( {& b3 w( H                        nextoff.append({'Gene':muteoff,'fitness':fit_muteoff})
) h( ]5 ^5 X, s& ]6 ?" e5 o/ [
, c1 [: h0 V+ C; F2 N            # The population is entirely replaced by the offspring4 Y! f) @9 e3 S5 X# C
            self.pop = nextoff# _" E5 S$ }9 [6 L4 u
* S! I% ?% @0 Z5 H
            # Gather all the fitnesses in one list and print the stats# A: k" B! F2 I7 U
            fits = [ind['fitness'] for ind in self.pop]" \+ r7 F' h9 ^4 X

* ^# w. ^4 Y$ a1 Y            length = len(self.pop)# d( H0 d1 e9 x5 W: j. \
            mean = sum(fits) / length
( z5 f1 @" h" Q/ H7 ?0 v1 w            sum2 = sum(x*x for x in fits)2 k% K5 A7 ]2 ?  B
            std = abs(sum2 / length - mean**2)**0.5
! U) A- Y  R0 o; S8 o            best_ind = self.selectBest(self.pop)& l, m  e# }3 N- d! G
! _8 q4 k8 V9 r- g! Q' j4 |; D
            if best_ind['fitness'] < self.bestindividual['fitness']:! v& H; @0 G9 O( K
                self.bestindividual = best_ind% g, W, D+ t! I$ N

6 U/ s2 h4 ?: ?) w4 Z' r8 f            print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))
6 j' @0 N9 c6 `            print("  Min fitness of current pop: %s" % min(fits)). P8 a) a8 J5 `( T# ~; n
            print("  Max fitness of current pop: %s" % max(fits))
  a% u( k9 N+ a2 E            print("  Avg fitness of current pop: %s" % mean)
. W& M  d# D4 t            print("  Std of currrent pop: %s" % std); K$ f5 F+ E7 @3 V$ W
1 U6 m/ M7 X' u+ v! N
        print("-- End of (successful) evolution --")   
4 T+ T: h( ]& w+ F, l# G
0 e. Q) M) l% N1 Jif __name__ == "__main__":
6 M. M: W' p( Z4 d5 I1 \3 A
5 T) X1 V/ M4 R' [    CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters3 `4 L. D: B) V. p

6 K: l! h, K& k# _$ Q  E0 W    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables% _1 S5 s5 i- g* G) n2 K( A5 U* o
    low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables
7 ~5 z, W$ ^5 |, M. }7 K    parameter = [CXPB, MUTPB, NGEN, popsize, low, up]# j+ ~6 @. v! Q. n) P

- d2 D) N- \1 ^6 L8 ]; ]! ?% D, p& Z0 U    run = GA(parameter)) R! P% ^) m8 X9 G6 V4 F
    run.GA_main()& h/ v3 ~( e1 t
————————————————
7 h9 v6 @1 F( J( V0 W& ~! p' a; W版权声明:本文为CSDN博主「bible_reader」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
& c/ X1 t. b% W9 q: X原文链接:https://blog.csdn.net/bible_reader/article/details/72782675! x4 d$ Q8 x& M2 g2 d' T9 m
5 D# Q+ R" I1 i) Y* i+ p6 ?
. ^' L. j0 X0 ^

作者: 1034228464    时间: 2021-10-12 18:46
python实现遗传算法易懂! C/ [6 i# g1 M

作者: lifekokool    时间: 2022-1-17 16:05
可能我有点笨吧,看了之后还是不知道该怎么应用某个问题9 o8 H  Z; I' Z7 P, W0 h2 A9 y

作者: 738391227    时间: 2022-2-19 16:36
0000000000000000000000000
/ ]8 q4 m: v- U7 S
作者: 852952290    时间: 2022-8-10 20:25
111111111111111111& g; U  V% H+ M8 y

作者: 2275929388    时间: 2022-10-9 14:14
遗传退货怎么都看不懂. P# a. v' r( e6 J8 H7 a+ j7 p

作者: wwyx。    时间: 2022-10-9 18:28
赞赞赞赞2 {* l% \$ j. C; v" r: c6 c3 j

作者: 2275929388    时间: 2022-10-10 09:08
566666666666666666666- v% Q% W. o6 v1 {* {

作者: 2580684929    时间: 2022-10-12 23:19
牛蛙,最近在看这个) Y1 _. S5 }9 h





欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5