数学建模社区-数学中国

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

作者: 1440359316    时间: 2021-6-19 15:17
标题: 遗传算法(python版)
1.png
+ C0 L" V/ n3 K/ @遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。该法则很好地诠释了生物进化的自然选择过程。遗传算法也是借鉴该基本法则,通过基于种群的思想,将问题的解通过编码的方式转化为种群中的个体,并让这些个体不断地通过选择、交叉和变异算子模拟生物的进化过程,然后利用“优胜劣汰”法则选择种群中适应性较强的个体构成子种群,然后让子种群重复类似的进化过程,直到找到问题的最优解或者到达一定的进化(运算)时间。4 U+ s# [' }; Z2 q, x- H( w

* J0 q& Q1 }2 [* \% ~4 ]Ga算法中的几个重要名词概念。; y# w' D4 h$ v1 v

5 t9 Y8 U( c  p% w个体(染色体):自然界中一个个体(染色体)代表一个生物,在GA算法中,个体(染色体)代表了具体问题的一个解。( z: n) M0 S5 f3 M. _& U. s- H
2.png
0 U# f! M" e$ k+ L- K1 B
& h4 o! `! U! C基因:在GA算法中,基因代表了具体问题解的一个决策变量,问题解和染色体中基因的对应关系如下所示:
' G9 d/ w% s1 T' v' t$ x* U
- T, ~* w5 L, `, K, V+ N 3.png 3 ~2 H5 F" t$ j+ i/ Z7 e, f. b" j( z
种群:多个个体即组成一个种群。GA算法中,一个问题的多组解即构成了问题的解的种群。
' H6 n7 a* n# C* N2 ~' u: L- O1 z" j' ~3 R. v( p% c2 {+ w2 d
2、主要步骤, q5 M. L( w  q. w$ e! h! A7 e1 l
GA算法的基本步骤如下:
) @4 n& ?5 q0 r; H0 e' [* |# e7 o' P- I: [! G( \
Step 1. 种群初始化。选择一种编码方案然后在解空间内通过随机生成的方式初始化一定数量的个体构成GA的种群。
2 i: v2 Q+ m; ~; T* r! F# P1 S/ O9 \* \% O# c0 y' p) k
Step 2. 评估种群。利用启发式算法对种群中的个体(矩形件的排入顺序)生成排样图并依此计算个体的适应函数值(利用率),然后保存当前种群中的最优个体作为搜索到的最优解。8 r, z7 e9 N* V; ]- d: {1 \; d8 U
5 d1 N2 R% u0 C# \5 {% z
Step 3. 选择操作。根据种群中个体的适应度的大小,通过轮盘赌或者期望值方法,将适应度高的个体从当前种群中选择出来。  X+ d4 Z' S3 G4 ~
' Z2 m9 [7 l8 v) H) }
Step 4. 交叉操作。将上一步骤选择的个体,用一定的概率阀值Pc控制是否利用单点交叉、多点交叉或者其他交叉方式生成新的交叉个体。
6 R- ?6 ^$ e6 k" r2 W( H3 j7 y4 J" m1 h5 ]5 O2 B
Step 5. 变异操作。用一定的概率阀值Pm控制是否对个体的部分基因执行单点变异或多点变异。* e0 j# \+ F( z4 F1 m6 `: ~; Y
6 }) u5 H: z9 j0 J
Step 6. 终止判断。若满足终止条件,则终止算法,否则返回Step 2。" o: u) {" R& G6 {+ ?  d9 a6 c

1 [+ f( t1 [6 U! b9 J流程图如下所示:8 }; G  D0 L6 f5 \. p
4.png
) D6 Y. ~' L! A: v! [+ u- M1 P5 h1 c
3、主要操作介绍
: h1 W* l( _* R- O% k3.1 种群初始化
+ q9 e# K9 {$ I- m  z  @2 a种群的初始化和具体的问题有关。比如一个问题有n个决策变量{x1,x2,…,xn}。每个决策变量有取值范围:下界{L1,L2,…,Ln}和上界{U1,U2,…,Un},则种群中个体的初始化即随机地在决策变量的取值范围内生成各个决策变量的值:Xj={x1,x2,...,xn},其中xi属于范围(Li,Ui)内。所有的个体即构成种群。当每个个体都初始化后,即种群完成初始化。
4 g7 i* n7 D( _1 J6 s( X) c* F$ N! z
3.2 评价种群
  S, ^2 N: I1 W7 W; k+ j种群的评价即计算种群中个体的适应度值。假设种群population有popsize个个体。依次计算每个个体的适应度值及评价种群。
; {2 e1 ~( E  O4 j7 Z
) X- {) S. l% e* \4 O5 b8 l3.3 选择操作$ c' O6 m# d# D2 k+ _$ D
GA算法中常见的选择操作有轮盘赌方式:种群中适应度值更优的个体被选择的概率越大。假设popsize=4,按照如下表达式计算各个个体的被选择概率的大小,然后用圆饼图表示如下。5 @$ l, s9 s5 I2 R& s& Y$ D" p

1 N4 v1 n1 a. t, H8 |P(Xj) = fit(Xj)/(fit(X1)+fit(X2)+fit(X3)+fit(X4)),j=1,2,3,4" I# k; Q. G5 V3 D5 ]/ H- `% b
5.png
- f, \+ r  |) W" `3 m7 o6 q+ L; h5 ]3 B- V4 x+ n9 v* z. G3 [
当依据轮盘赌方式进行选择时,则概率越大的越容易被选择到。" x; v3 c7 h) d  V" t

0 S4 w9 P0 n, |7 i3.4 交叉操作
1 g4 g1 B+ F; \交叉操作也有许多种:单点交叉,两点交叉等。此处仅讲解一下两点交叉。首先利用选择操作从种群中选择两个父辈个体parent1和parent2,然后随机产生两个位置pos1和pos2,将这两个位置中间的基因位信息进行交换,便得到下图所示的off1和off2两个个体,但是这两个个体中一般会存在基因位信息冲突的现象(整数编码时),此时需要对off1和off2个体进行调整:off1中的冲突基因根据parent1中的基因调整为parent2中的相同位置处的基因。如off1中的“1”出现了两次,则第二处的“1”需要调整为parent1中“1”对应的parent2中的“4”,依次类推处理off1中的相冲突的基因。需要注意的是,调整off2,则需要参考parent2。
- T) D; a" F0 T5 `5 ?4 x7 \! m
2 S! z. Y$ D) X 6.png
& G1 [4 n- \! f, ?. |- J, `0 E6 r6 j0 V
3.5 变异操作
0 Z% a: {6 j8 t* M$ W: L变异操作的话,根据不同的编码方式有不同的变异操作。% k* r  n+ ]. T0 U
+ Y' d, s' J3 s9 b( K# {( Z( g
如果是浮点数编码,则变异可以就染色体中间的某一个基因位的信息进行变异(重新生成或者其他调整方案)。6 N  i* L; P8 t) M, ~% F

$ x. Q/ D" y; d  a# n$ [& Q- u 7.png
5 D+ N5 f' j5 x0 \如果是采用整数编码方案,则一般有多种变异方法:位置变异和符号变异。# ~: j+ ?& Q3 ]
; A8 |3 {5 B' {8 t
位置变异:
% ~+ g9 {/ B, s 8.png 4 n" X) C6 B  M( m! O- }8 N
0 G* q) U; k+ x2 J7 m
符号变异: 7 {1 O" K1 J: r& }5 R- t& C3 U! q
9.png
& r4 J$ s9 Z# A: C  E+ ^6 U1 D) G" y3 ?) T: z
4、Python代码# N( @3 y) y" p4 ~; j# W' i
#-*- coding:utf-8 -*-( }" v! c1 ?/ S; h+ a8 e

3 g4 y8 ~% {4 O5 \9 ?import random
% m  \4 k, [) n3 @" `& |import math
+ r, n5 s6 c$ r% q' Y- S( Sfrom operator import itemgetter( i; a  \1 Z* J- g5 O- {0 D; s7 L* C) |
: Z; O4 o4 Z+ X3 P! @
class Gene:/ n% v/ k/ C8 P
    '''& c' o- ~( m+ x! e; ^/ L
    This is a class to represent individual(Gene) in GA algorithom* _  E% g/ o4 t' W/ Y2 i1 J
    each object of this class have two attribute: data, size* g* J- b0 W9 ?! k
    '''
: p0 R- N) H7 K4 U  a! h    def __init__(self,**data):
/ i" @7 c; K) n" e* b/ i# y  k        self.__dict__.update(data)      
" f8 c; U. Z& ~3 r        self.size = len(data['data'])#length of gene% S0 p9 u: a5 L, f
: \" Y- B. _3 c" y( J6 h

) {# \5 g; o: j+ w; H) ~class GA:$ b4 D% q. k# m/ [# N4 u
    '''! n/ L3 e: e. Z9 x6 E4 J8 e2 {' X0 K
    This is a class of GA algorithm.
. H+ m9 q. R- ]! t1 D6 Z. o    '''
2 \5 g, i, K" f8 e8 }0 Q  C    def __init__(self,parameter):/ }+ G* M" G/ ~3 F; D3 p
        '''
! B7 y6 ^9 |( O$ p5 d. Z6 G        Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .' T% ?  J2 V  e8 _: F
        The data structure of pop is composed of several individuals which has the form like that:! \9 R+ u' z, f7 m: t

& i* J% j4 {) B6 o, Q* h+ P0 {        {'Gene':a object of class Gene, 'fitness': 1.02(for example)}# ~# G* H5 Q) Y# j
        Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]
- g: Z4 i# m5 B$ f
- @. d% y, V, O        '''3 x9 B& r4 n8 p! ^* Z9 u
        #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]
3 P% {/ T- I% i& v" N        self.parameter = parameter: s+ {- b6 |* X! y4 t

7 s, ~3 S: ]: m2 `0 e$ T. m        low = self.parameter[4]
' a8 ~; o0 P$ K7 e+ Q        up = self.parameter[5]0 D' H6 @7 n( Z& F; d* x  c
0 T5 ]& h! l4 y% G, t7 o
        self.bound = []% P, B  s/ t/ Z% m. e% @
        self.bound.append(low)
% r  ]9 |3 o% r- w( O' I        self.bound.append(up)$ k- z5 i4 D6 ?. z& k& P( C
5 z! O0 r. D/ d  V, w+ a- |
        pop = []
$ X8 L# p: K! Q, K, R. b: r: \        for i in range(self.parameter[3]):- z8 d$ r& o$ i2 R0 B) \
            geneinfo = []+ @+ u: a/ c! y3 _: u
            for pos in range(len(low)):
3 t0 H' T5 c% W4 J! i6 A2 P: ?                geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation
; d8 {1 E- i% M  O) ~- K1 m* O& d5 y' S/ n3 X$ u
            fitness = evaluate(geneinfo)#evaluate each chromosome' E4 u4 ?1 L: ~
            pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness! n  e, c. b0 A! a6 e8 V+ w

3 b; j6 ]# M! o& L: F        self.pop = pop
! _9 i+ ?3 z1 A- C4 H        self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population! w2 j: e/ ^" R( c! v
1 E, K% i3 \6 b8 h
    def selectBest(self, pop):& r9 O- q/ c& {4 W3 i( A# R
        '''
( o' c8 r% s8 r        select the best individual from pop, _/ N2 g, x6 Z$ D% l0 ?6 [
        '''# E" `( e0 d& l* ^
        s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)
' T! f9 x0 a6 g8 x5 I* ]# [  ~' N        return s_inds[0]
% k! O9 _8 G. w1 A* |6 O* G$ i9 @5 S4 a7 }  v
    def selection(self, individuals, k):2 Y2 V3 F* `" c
        '''/ R& ~7 ]& Y: |! b* s# A4 F
        select two individuals from pop4 ?& y- A4 l! f5 P6 m
        '''
, }- h" K* _: x. y6 v        s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness 1 M7 ^9 R; R3 c" O- a  p1 E
        sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop9 h$ V2 ]" H  |8 q1 R5 \+ G- k

! U# G) a; w2 n& S2 p( V3 F5 I# y% x        chosen = []5 K5 g; k: e; g6 O7 J; A6 v1 }
        for i in xrange(k):; F# n7 o, w3 q  }! R: f$ o
            u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]
! A" [$ P! `( c2 x( Y, e1 A            sum_ = 0" c) Q' n, c  B! O) s0 N+ i; d
            for ind in s_inds:
4 q( E! u0 L3 ]8 w- w                sum_ += 1/ind['fitness']#sum up the 1/fitness
3 \' t! M- d/ T, h2 f. p                if sum_ > u:
7 i1 y) p2 l7 e  r+ T; u                    #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
* q2 E9 S$ w! B6 ^( y! e                    chosen.append(ind)
3 q; v8 f& H) y! \# X4 A: Y                    break
$ U. t0 i1 ?7 g9 C9 X! R* y/ o
3 Y/ ?+ k% r! r: o' y$ {        return chosen   
! w. j! a' o; t- b* J0 J
1 f# q" s* g2 o( h7 D) J( o. E% o( x% Y1 c; h
    def crossoperate(self, offspring):
( b# H5 p& w. X. L: l! d! e6 {, W        '''8 |1 X6 n9 h" ?+ ]
        cross operation1 T" t6 G0 G2 @! E
        '''& |5 l* X& G2 ~( E) n3 O
        dim = len(offspring[0]['Gene'].data)6 {6 `9 f) o8 x( F" ?
- k1 T$ _# p6 B
        geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop% [5 c/ V( A  q+ ?  S* E
        geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop
9 ?$ f$ u! G6 K
/ x: v$ N. p# r: k) B: [( w0 `        pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1, 1 ~9 x9 ]- N+ F6 A" d" A1 k
        pos2 = random.randrange(1,dim)
; J& C" K. }4 `/ n6 C4 ^5 G4 I# c  h% @" X+ g
        newoff = Gene(data = [])#offspring produced by cross operation& a) ^/ V' z/ n8 P
        temp = []% ~0 c+ v2 R$ Z% I% s! d
        for i in range(dim):
0 _6 Y7 @, {8 q: U/ K            if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):0 L  H/ U. h. b7 a! _
                temp.append(geninfo2)
: k5 L- c) [! o                #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)]
% s7 [: _4 }" C' L& w- v            else:/ u, |# ?2 y+ K; q$ \- ?! `' A# `: H
                temp.append(geninfo1)' H% l+ i4 d$ Q4 d& r$ v# P
                #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]' o& I0 D4 O# ?% X  f8 M( i: H
        newoff.data = temp9 X" _9 p" a7 y( R
6 y. |" A' k7 \  }4 W
        return newoff
- E6 d, B) q& k; n
6 X0 P4 Y% i( O. ~
, S% @$ v/ w* m5 r. Z$ v. X    def mutation(self, crossoff, bound):. y! ?3 \1 k0 a( u6 l0 g; w- l- @1 J
        '''
% ^2 |- n: n/ Z; Z$ `        mutation operation
: v, A2 y! J. p        '''. y& Z) w3 P5 U/ \: j. p
# B0 d; B: h3 y1 t" E8 j5 @
        dim = len(crossoff.data)
/ t- G4 E! O; K" ]7 a1 V6 |5 o, K' S7 T2 G: Q
        pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.
) `' F' u# O6 V- z" q& {% f
7 v4 j0 y, a' T9 @) l9 S        crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])
8 F4 O$ q3 D/ ^/ U; R; R  [6 T        return crossoff+ s! W/ y& E/ C6 j
7 Z* F" M' T& _& Z
    def GA_main(self):
2 C3 r% T4 P2 a9 Y; G" J7 f5 {        '''
9 [& s) s5 v& p! |        main frame work of GA
' y5 E8 T. }1 U- p% c; n        '''
/ J( t: V% Q9 [- e8 H6 @' M3 e1 e) g/ B' P' x9 z9 Y( c& R
        popsize = self.parameter[3]
$ t: ?. b- K& F6 J* D
6 B. j# i; r3 j  W  M# B9 K        print("Start of evolution")
+ y; _$ w* x. c5 J$ Y4 J) `0 f( v- K6 U
        # Begin the evolution  q: L) S8 X; [5 v! g( k8 v
        for g in range(NGEN):
) W) I+ o6 K" q) X4 g
( D6 i( x9 h8 M2 g! H5 Y' U* [, U            print("-- Generation %i --" % g)      
! A0 a; i/ n0 s, [: z. Z* w; ~# N% ~* k
            #Apply selection based on their converted fitness
- |) A, I& E' q* d            selectpop = self.selection(self.pop, popsize)   
( O8 ?& `. X5 I6 W5 A# Z9 k/ F) o, f$ E* P; J% c5 u
            nextoff = []   
# _. V: o- k5 r  ~' ^# W! V0 l6 @; t            while len(nextoff) != popsize:      / C8 x5 D$ b( b# M( X
                # Apply crossover and mutation on the offspring            
' B6 r. \2 ]' w8 j* j$ X' E: ^  H
                # Select two individuals5 g8 N* t% m, u3 i$ {
                offspring = [random.choice(selectpop) for i in xrange(2)]% O; i+ ^5 L% `# d. [

7 l$ l3 z4 o! L1 o( e: K5 ?                if random.random() < CXPB: # cross two individuals with probability CXPB
) k+ A( Y( l8 S                    crossoff = self.crossoperate(offspring)
3 s- |2 Y. r$ H9 Z" H$ |                    fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals           % X- x/ B5 V# O
) h7 u( o2 W: E+ {
                    if random.random() < MUTPB: # mutate an individual with probability MUTPB* w: j. N$ q3 k
                        muteoff = self.mutation(crossoff,self.bound), F& A. w5 l8 T. C, o3 h  T
                        fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals
$ t4 M; h9 T$ J7 T                        nextoff.append({'Gene':muteoff,'fitness':fit_muteoff}). Y8 I) q0 V2 V9 N# C. q

7 b# s; }3 L1 |4 Y            # The population is entirely replaced by the offspring1 |$ j4 N9 ]4 C% \
            self.pop = nextoff
# @/ U) k0 f- J7 P1 q
5 O- R, a6 h) {            # Gather all the fitnesses in one list and print the stats
6 _) k. w2 h( e1 y8 Q            fits = [ind['fitness'] for ind in self.pop]* M0 r5 f* ]( Q! K$ ?/ T+ B; J

5 [4 i9 D* S, U7 e5 ~( ?' [+ [            length = len(self.pop), J' @/ T/ M: l2 Z' p
            mean = sum(fits) / length4 u0 D4 a! p. q- ?4 f
            sum2 = sum(x*x for x in fits). p2 t( [2 R! b4 V+ X, I, M; _
            std = abs(sum2 / length - mean**2)**0.5
& I4 k7 @4 `$ |2 \6 X4 Y) }            best_ind = self.selectBest(self.pop)
% O" j2 b, v1 c& p- K
9 j# D# ?: U# T7 s& @( E- X& N: `            if best_ind['fitness'] < self.bestindividual['fitness']:
2 ~9 s: v- D1 y+ E5 Q/ @                self.bestindividual = best_ind
0 @3 k$ L7 o9 W$ z  M! B) o( ^  {- A7 f7 m5 M2 G
            print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))/ i. [9 @& R" f
            print("  Min fitness of current pop: %s" % min(fits))
9 _1 x1 B' F( t' D- f            print("  Max fitness of current pop: %s" % max(fits))! d) u/ n; P. J* u3 Y# V4 _7 v
            print("  Avg fitness of current pop: %s" % mean). m$ Z+ X1 t  ~! Y! g
            print("  Std of currrent pop: %s" % std)
3 a, y2 S2 E' ^! {8 Y1 z5 r% v/ s2 ^( G# h( Y' E7 P* Y$ N2 d- A( E+ H
        print("-- End of (successful) evolution --")    ) {. N2 n, ?# I

2 s  S& w2 q1 m; j% F# \* yif __name__ == "__main__":
+ p) |, f# {3 Y1 `- Y$ M9 l" [1 N# E4 v' T5 |0 m# X# y
    CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters
) p) V$ T# w# f7 b# c' }$ x
; E9 @' k, k8 y4 D6 C    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables& B& z  V# b: u! m6 P8 b9 a) i
    low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables- f6 _* }2 S: \
    parameter = [CXPB, MUTPB, NGEN, popsize, low, up]
9 _9 ~* z9 t1 \9 X5 j  @! r" U' ]2 R1 p+ I
    run = GA(parameter)
) W, U: D6 Z: ?$ o2 K    run.GA_main()
$ X1 @) `1 l7 i% _————————————————
0 [+ ~7 B' ?! E2 H版权声明:本文为CSDN博主「bible_reader」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
4 m5 Z4 P% B( [* |原文链接:https://blog.csdn.net/bible_reader/article/details/727826756 c% N; T) ^  x* N% b

+ ~$ U7 v6 D8 x, e4 I8 h
7 y& m* t( X0 x5 g/ b: Y
作者: 1034228464    时间: 2021-10-12 18:46
python实现遗传算法易懂  `2 o2 a5 ~* p

作者: lifekokool    时间: 2022-1-17 16:05
可能我有点笨吧,看了之后还是不知道该怎么应用某个问题/ a1 }1 S6 H* J- w/ O$ `* K

作者: 738391227    时间: 2022-2-19 16:36
0000000000000000000000000
" [' T) f% l: _" _8 ?
作者: 852952290    时间: 2022-8-10 20:25
111111111111111111
' d- @3 e. j% ~" P. U# L
作者: 2275929388    时间: 2022-10-9 14:14
遗传退货怎么都看不懂, T( c  Y% z$ l, Z: ~5 j" D) M

作者: wwyx。    时间: 2022-10-9 18:28
赞赞赞赞# ?8 C$ M" a0 e: y, ?: ]

作者: 2275929388    时间: 2022-10-10 09:08
566666666666666666666
; ^% b' m- S/ V' W5 z
作者: 2580684929    时间: 2022-10-12 23:19
牛蛙,最近在看这个
' n: `/ {# X& j" C+ K) Y! c




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