数学建模社区-数学中国

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

作者: 1440359316    时间: 2021-6-19 15:17
标题: 遗传算法(python版)
1.png , W5 b2 m. b' |  w) Y
遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。该法则很好地诠释了生物进化的自然选择过程。遗传算法也是借鉴该基本法则,通过基于种群的思想,将问题的解通过编码的方式转化为种群中的个体,并让这些个体不断地通过选择、交叉和变异算子模拟生物的进化过程,然后利用“优胜劣汰”法则选择种群中适应性较强的个体构成子种群,然后让子种群重复类似的进化过程,直到找到问题的最优解或者到达一定的进化(运算)时间。
( B. ]! c' p; m, t7 I1 k
/ E/ O; y( g. L& e6 `Ga算法中的几个重要名词概念。( r9 @& b/ g% m0 c
+ d/ o4 D8 m4 d3 g# o5 x
个体(染色体):自然界中一个个体(染色体)代表一个生物,在GA算法中,个体(染色体)代表了具体问题的一个解。( ~7 m9 u( }) u, |4 o
2.png % C3 {/ L! B6 E: E+ k8 s% \

1 N5 u$ R& Z/ t3 y# n# T+ m基因:在GA算法中,基因代表了具体问题解的一个决策变量,问题解和染色体中基因的对应关系如下所示:4 d  n& c7 c* n: T

% u8 B0 i8 P' t4 g) b/ ~8 N 3.png
5 {% |* S2 X7 C- k种群:多个个体即组成一个种群。GA算法中,一个问题的多组解即构成了问题的解的种群。% a9 z2 h' Y- p2 x$ q

& _, m( @- V, C5 [' }) r2、主要步骤) n0 U$ s: Q3 [& q* B
GA算法的基本步骤如下:7 X* ~5 K( R" G! {) b0 T

% w+ e5 @* w+ y5 o6 k. }+ w, h8 r  |Step 1. 种群初始化。选择一种编码方案然后在解空间内通过随机生成的方式初始化一定数量的个体构成GA的种群。  F$ y+ k& E3 }" ^) c) `
6 y$ M& v, |0 @, K8 J+ R
Step 2. 评估种群。利用启发式算法对种群中的个体(矩形件的排入顺序)生成排样图并依此计算个体的适应函数值(利用率),然后保存当前种群中的最优个体作为搜索到的最优解。
* q3 e/ ?% t8 O4 I7 W, L- m, ~+ e. C) }4 S9 O
Step 3. 选择操作。根据种群中个体的适应度的大小,通过轮盘赌或者期望值方法,将适应度高的个体从当前种群中选择出来。/ n* y' o+ Y- W! q  @

% T" I" p5 E$ {3 oStep 4. 交叉操作。将上一步骤选择的个体,用一定的概率阀值Pc控制是否利用单点交叉、多点交叉或者其他交叉方式生成新的交叉个体。) Z- d. t& Q5 y$ }0 L

9 q  y' z' u4 G, t% E6 EStep 5. 变异操作。用一定的概率阀值Pm控制是否对个体的部分基因执行单点变异或多点变异。
( w6 |" {3 Q  g+ ~4 U) K$ U4 l
/ ^! ?) m* t+ P! c. TStep 6. 终止判断。若满足终止条件,则终止算法,否则返回Step 2。3 p2 F+ N" Y3 @4 [4 z# I
' a& ?" ^2 D+ |* ]' G: M+ s9 E7 C
流程图如下所示:
  p/ I$ T' S* Q: p0 b 4.png - k+ Q6 e4 p( [. U
/ r4 }0 w8 z7 `- e/ {
3、主要操作介绍9 E5 h  B* G+ t# `
3.1 种群初始化
9 E4 D% J1 a0 P; {1 r$ q; O种群的初始化和具体的问题有关。比如一个问题有n个决策变量{x1,x2,…,xn}。每个决策变量有取值范围:下界{L1,L2,…,Ln}和上界{U1,U2,…,Un},则种群中个体的初始化即随机地在决策变量的取值范围内生成各个决策变量的值:Xj={x1,x2,...,xn},其中xi属于范围(Li,Ui)内。所有的个体即构成种群。当每个个体都初始化后,即种群完成初始化。3 ]- s% V+ }0 f- P8 D6 ]
0 i: b' n& L3 G& i7 \* Q
3.2 评价种群; @3 \% H1 z5 _) o& ?- y
种群的评价即计算种群中个体的适应度值。假设种群population有popsize个个体。依次计算每个个体的适应度值及评价种群。5 L" Z7 }: I) h. p" r/ S$ Q# z2 g! Z
$ K& |; ]% A" h* _) c8 m
3.3 选择操作; N% U$ |$ e; ~1 |4 K1 y3 |( Y
GA算法中常见的选择操作有轮盘赌方式:种群中适应度值更优的个体被选择的概率越大。假设popsize=4,按照如下表达式计算各个个体的被选择概率的大小,然后用圆饼图表示如下。
7 R# m, d7 w* w' H4 O
7 s  c) l. |+ }, ^) A; ^+ N3 jP(Xj) = fit(Xj)/(fit(X1)+fit(X2)+fit(X3)+fit(X4)),j=1,2,3,4: o  P7 B5 W6 t' K- Y( r+ n
5.png
) ^1 Y1 b1 H$ a) }3 g, j4 l8 H# e) c0 D
当依据轮盘赌方式进行选择时,则概率越大的越容易被选择到。
0 Y+ A3 z" M3 r* e' p9 {6 `5 @. k6 u# y- l: Q) j6 g
3.4 交叉操作8 p  d+ J* u7 t1 _) M
交叉操作也有许多种:单点交叉,两点交叉等。此处仅讲解一下两点交叉。首先利用选择操作从种群中选择两个父辈个体parent1和parent2,然后随机产生两个位置pos1和pos2,将这两个位置中间的基因位信息进行交换,便得到下图所示的off1和off2两个个体,但是这两个个体中一般会存在基因位信息冲突的现象(整数编码时),此时需要对off1和off2个体进行调整:off1中的冲突基因根据parent1中的基因调整为parent2中的相同位置处的基因。如off1中的“1”出现了两次,则第二处的“1”需要调整为parent1中“1”对应的parent2中的“4”,依次类推处理off1中的相冲突的基因。需要注意的是,调整off2,则需要参考parent2。. U. |- G; M  ]4 I; {2 R( k
9 z6 ?4 w+ O/ _, ~9 X3 X  s9 p: n% F
6.png 9 a5 d9 o) h3 w7 O$ b

1 B9 X& i1 j5 T1 R; I' j3.5 变异操作
  z, ?: _, h8 P( `3 O7 P变异操作的话,根据不同的编码方式有不同的变异操作。, F. @% U# T4 G% f

+ N, a0 O" ~* p8 @5 g3 ~9 I如果是浮点数编码,则变异可以就染色体中间的某一个基因位的信息进行变异(重新生成或者其他调整方案)。
! F8 \, H/ q- F
- t2 N, d7 X: y5 { 7.png / }2 A1 m: ?) a. N
如果是采用整数编码方案,则一般有多种变异方法:位置变异和符号变异。6 a- \4 a% `  I* \* G$ @) Y  X9 j# F" T7 c
, w' _% d- l0 a
位置变异:
; _. I% t$ e% I( Q0 n" r/ o 8.png 3 |+ I" r" ?0 L  ^) v# X, o
/ M2 K  p; z/ w7 z- C( F7 z
符号变异: 2 k, f# A# \4 {2 q
9.png # [+ ?; P0 C# J6 G0 g: ~4 k! g

! @' p% i# l4 K+ j$ V4、Python代码
; {% o/ @! D) }* H#-*- coding:utf-8 -*-
  B; Y0 B3 I1 W( z$ }& F4 N$ Y) K" t; \# R* r# D; z0 j9 n
import random
/ J% L+ R' ~: t8 e$ R8 \) Nimport math9 Q; K  ~6 I! [
from operator import itemgetter
  E, q9 F4 v9 I: H# n  Q% u- p; r- j' A4 M
class Gene:
# c7 M1 k: f3 I1 `. J    '''
9 _; d" W: O5 m! i7 Y; I7 e- T    This is a class to represent individual(Gene) in GA algorithom
0 Q$ j, E) B. C3 P- j6 D) P    each object of this class have two attribute: data, size% g: [. i# W$ y; j
    '''3 A9 E3 h& |: m. y5 u  U5 ~
    def __init__(self,**data):9 J  S- q: M$ O) q- s. _/ \
        self.__dict__.update(data)       1 H' C- T- ~. f" I" E  H% u0 U
        self.size = len(data['data'])#length of gene: ?2 ]! ~& V8 B! G2 u9 p

5 K/ P$ ~- u5 n% R" e( j
# s2 R# N) n0 w, }9 L  ]1 c2 ?class GA:
5 ~$ m5 Y1 V/ e7 ^' f) ^; v    '''
* U6 P+ O* l  v' r: c; _& `    This is a class of GA algorithm. & L5 A2 l4 {' l+ l; Q# f
    '''
! j# T6 x9 x" S, U) }    def __init__(self,parameter):
; j  a; K7 T2 o' M* `        '''
5 L! B) S% G6 K6 l4 P5 r  q  g        Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .1 T& A1 U- y( A/ g8 a
        The data structure of pop is composed of several individuals which has the form like that:: [. Q8 S/ S* Y, M- ]( {. Q9 P

  g2 f  d, Y- k, n- h3 [5 C        {'Gene':a object of class Gene, 'fitness': 1.02(for example)}
/ `5 U- i* i6 z: S5 J4 U% g        Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]" u& A$ Y" U2 L) h; V8 P; P& S6 k
2 v% t! T$ m* ~1 t6 K
        '''
" b: U, U0 }& p) M, y  l        #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]6 ~' t; G: z9 e5 o
        self.parameter = parameter
& f% b  y0 j8 Y( {$ y% a0 A5 G5 f7 F/ D1 T' d! ?3 n$ r
        low = self.parameter[4]
' P# b, H! n8 Y1 h        up = self.parameter[5]0 G. Y. h. x: Q
) e; t5 W7 w; p2 \' M
        self.bound = []
9 X/ l" H. Q8 J7 |6 c) w        self.bound.append(low)
; S! C$ U3 m; P; r. M2 W" S3 ~        self.bound.append(up)
1 @6 r$ b) `8 o3 l9 V- j& A! P, R
" R) O5 ]% [. M" T' ]7 i4 [5 X        pop = []2 q1 b! R6 u# L/ N" a
        for i in range(self.parameter[3]):
5 q1 Q& g$ Y: `! @            geneinfo = []
- i5 u: p) c8 D5 K; N3 @  Y            for pos in range(len(low)):
- C6 Z4 u5 X: P: }6 I: x                geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation
9 I1 r: z/ Y) _$ o1 a( t7 a* e! j/ o" F* k" u2 x
            fitness = evaluate(geneinfo)#evaluate each chromosome
" i4 n! D% x2 I* s% q            pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness
: I9 b* L* c. T2 B. z3 n
2 `( |, H1 N1 y/ Z1 x- J7 y) C        self.pop = pop+ A' i: L$ Q& t3 v8 K9 E$ Q- X* D
        self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population
" n- S* G3 q3 D$ u% [1 E# ]$ A- p, c: [
    def selectBest(self, pop):& e' m% `, W8 U. H* G
        '''
- i& l; u, l& @7 M; t, T, I/ O        select the best individual from pop
/ f8 q+ d# Q! _( k% f* Y+ D        '''1 u  \5 z) c( k# E+ s' A
        s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)
; C7 O/ t' k2 j! d8 s$ s        return s_inds[0]
$ r! d: X& j- T1 Z: m" G
$ b+ Z1 N3 m. v. C$ e5 t* @5 P  C    def selection(self, individuals, k):# L# y% D$ |& e8 J
        '''
/ B5 i3 `* x( T+ o        select two individuals from pop
+ C* q- S+ a1 H$ e        '''9 U" x- d  s2 x# D; V
        s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness
; B& C5 P( a% z4 p0 _        sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop
, t2 `5 o+ m- w  @( ~2 L0 x% c! l4 O/ M" Z2 T$ m
        chosen = []
% c; v% R: F+ I0 A3 n        for i in xrange(k):! p* r( z% E+ |% @" J- B
            u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]
$ ~2 B$ J" I& k" e# q: _- b            sum_ = 0
+ n1 Q+ {2 @0 C) L3 Y- h' ?            for ind in s_inds:
8 M- I$ `6 N/ f8 Z/ c" O                sum_ += 1/ind['fitness']#sum up the 1/fitness
9 A- R4 r& c) I6 O( @* ]                if sum_ > u:& @+ e$ x" R3 L$ e2 Y9 Q
                    #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- {" t2 R. b1 M6 r
                    chosen.append(ind)2 e% K: P8 B/ t, h5 v
                    break
2 g+ L7 j7 i" I; k; `
6 B, H. u$ f# P        return chosen   
2 T1 C) {1 q2 l, K" F! S& t) ], |" m8 k& |. P

* d: p2 b: Z$ l% d% i6 ?    def crossoperate(self, offspring):
& l' ]% X& z9 j/ ]- n5 m        '''2 I( u% r) ~5 G7 P
        cross operation
! }. D* ^' y& z' j, l( h        ''') [$ z7 J& @5 f- ?$ T
        dim = len(offspring[0]['Gene'].data)
8 v( m% K) `2 r$ v6 f7 P- q4 U. i$ g- n2 z
        geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop0 b' Q$ X* n6 `' L  ?+ Z
        geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop( F9 J3 a# q  v. d5 E( N& _
( K) F/ S  c6 f- N& ]: p8 w: D/ P
        pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1,
/ {2 ?2 t) C2 R$ T0 Z; _        pos2 = random.randrange(1,dim)) @1 q8 E# E6 U: [3 H% t6 k0 s
6 ~  |% ]% Z5 w5 m+ D1 ~8 s
        newoff = Gene(data = [])#offspring produced by cross operation
) P8 U7 d+ l( ~; h0 M- E        temp = []) g5 s+ z. x# V5 _: e2 U5 A9 [6 {5 `
        for i in range(dim):) K( {# Y4 ]* @& v
            if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):
6 P( y/ b0 y3 B4 W) J) Q5 \                temp.append(geninfo2)
$ P" v5 d% V7 Q3 y2 H$ p! b                #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)]
! x0 A9 A/ f$ a  R3 t2 S1 R            else:
, t5 X9 }: j' F' R6 I- T8 I% w6 X: C                temp.append(geninfo1)/ R& R1 a4 D, g
                #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]0 r6 h- K- H7 [+ M9 L0 z3 |4 k
        newoff.data = temp7 }, g& f/ K4 `$ a' X. U+ o% D* Z

3 b* F" D  @# x7 K+ N9 Z        return newoff# y: ?/ [5 l6 f4 A7 |* `

; i: F+ j1 b$ ?! a3 E0 ~6 M" G; f4 o' r7 I6 }  c( L5 ^& p
    def mutation(self, crossoff, bound):
2 z2 P& ^& D' K. m/ f! i        '''
* l( S5 L) A6 m7 G+ G* @        mutation operation
1 S: l& N1 |9 A$ N) R        '''
1 z9 A9 u8 t$ S
9 ]5 @0 X  j2 J        dim = len(crossoff.data)% s. D0 u* _* r9 Z; N1 H- E
  Z. w, F/ h3 G4 F
        pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.
  E% V+ h- Z: q
+ }# ?& v  }& M" z        crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])  e( ~  h' i! N+ X5 S+ _$ ~
        return crossoff2 L5 H8 L$ X; T3 A4 j

" ~# z$ K) X% f% |: V    def GA_main(self):
5 f: ]; k1 i8 p) z: o: D        '''
( u6 k1 G3 D* h7 c        main frame work of GA8 Q+ V) `) P! X* T9 E
        ''') e3 H; c* v5 Y! H* u3 u
% R4 W& ^, ^& O2 R" z' J( z2 _/ ^$ H
        popsize = self.parameter[3]( Q6 E2 b. A8 r

& \' u( a- @  o  y' r( j) w7 L        print("Start of evolution")8 ?' a9 X( p; t" l$ Z" V

( T# d3 k; C6 M' ~7 D5 U        # Begin the evolution
9 g- Z* u  ^/ Z3 K, f5 Z1 w        for g in range(NGEN):! u$ \3 C* T& ?9 R/ i2 Q

* ]) ^% j+ s6 R) H5 A3 _6 J# A            print("-- Generation %i --" % g)      
6 r0 b, j" F' c
- z. l4 v) I  r            #Apply selection based on their converted fitness
7 a3 r6 k5 }! K4 m6 o8 j            selectpop = self.selection(self.pop, popsize)   
9 t6 a2 }$ l1 J8 f
% \/ W: l1 ]  ?) ?. V1 l            nextoff = []   
" y4 J6 S. w. J. J            while len(nextoff) != popsize:      
# M. q" D+ T2 u, ]1 `. |                # Apply crossover and mutation on the offspring            9 [3 a7 [; W0 B# F' r3 k% E
- A/ P1 Z  i5 @8 D- l
                # Select two individuals
/ u6 r# Y* s; }. ^* r                offspring = [random.choice(selectpop) for i in xrange(2)]
* k- ]8 R' t3 l/ n4 ?4 U2 Q$ P
8 o3 d. }- U- I3 d                if random.random() < CXPB: # cross two individuals with probability CXPB
8 z1 _! [& G% t0 N                    crossoff = self.crossoperate(offspring)9 v3 N1 L4 I6 m* z( r. C% F+ V
                    fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals             g. E. R1 J2 o. P& y# \0 i6 I

) h5 l' i& {0 X( \1 j1 X+ [1 G5 S                    if random.random() < MUTPB: # mutate an individual with probability MUTPB
" v4 \7 l' t! V7 J  F                        muteoff = self.mutation(crossoff,self.bound)
  m7 L7 F" z$ d4 m- C+ q/ p, A3 e0 Y                        fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals
+ Y6 z2 u4 Y0 m7 w* I                        nextoff.append({'Gene':muteoff,'fitness':fit_muteoff})) [* K$ H/ H( {+ A3 O/ c

9 q# f: R# S# s7 B            # The population is entirely replaced by the offspring1 G# T1 ~+ I3 E9 m/ X
            self.pop = nextoff2 Q8 _. U8 h+ ~" F
! R. p) s' |" w# W% l
            # Gather all the fitnesses in one list and print the stats
, Y$ x/ g1 ]) y            fits = [ind['fitness'] for ind in self.pop]- A# v  P1 B& B, R; T  j

4 B- ?+ H3 R( T8 y            length = len(self.pop)
/ u/ n, M8 N  J+ x, t+ n+ e" H            mean = sum(fits) / length
3 t6 Q& I" I& X- Y            sum2 = sum(x*x for x in fits)
, i" s! `7 A7 n+ Z+ X, }5 U            std = abs(sum2 / length - mean**2)**0.5! T5 A! H+ p& F
            best_ind = self.selectBest(self.pop)
2 k. m3 G2 `$ O2 E
1 \- ~5 i/ `  u            if best_ind['fitness'] < self.bestindividual['fitness']:1 I$ t, |5 c! i( z3 {+ u9 E" q/ G
                self.bestindividual = best_ind5 }6 e% I# E, A; ~6 a

8 r1 A' c. q! D1 w8 h            print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))
0 B, j" F# K( J9 ]! X# K) q! ^            print("  Min fitness of current pop: %s" % min(fits))
  B: _, w8 z( L& F            print("  Max fitness of current pop: %s" % max(fits))
6 m" U& k7 |4 x) I5 ~. ^7 D            print("  Avg fitness of current pop: %s" % mean)* x# I# \! I3 f" `4 V
            print("  Std of currrent pop: %s" % std)
( |" F' o$ t. A
# W( A+ H7 a8 A6 u        print("-- End of (successful) evolution --")   
2 S% I9 E/ r* Q- R7 v
/ V! I7 o  k& K2 F! [if __name__ == "__main__":
) K- k4 R5 V/ d- X$ [3 J1 n; x8 B) |
    CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters
+ _' t2 I$ l$ l' M; p' T( d; J
8 n$ M+ F# l! Z3 c1 Z: x    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables& s" z( Q! p# C: z; b0 {
    low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables
, @- B& D3 i; g9 P; J    parameter = [CXPB, MUTPB, NGEN, popsize, low, up]
% y( ]) g& J$ w3 s. y4 Q; `6 f- }6 B3 k
    run = GA(parameter)
3 J& P3 U# d* {" R! _    run.GA_main(). j1 {  o" Y+ |$ u
————————————————
# ]& }6 n6 ?0 X$ w' k版权声明:本文为CSDN博主「bible_reader」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
1 r9 }5 m8 U  M' Z原文链接:https://blog.csdn.net/bible_reader/article/details/727826756 f- c5 u, A  U: A5 w6 S
. L1 f" ^0 ^+ R/ H) Y, k6 z) L
& [2 h+ N% [& ]/ K" f* \& N

作者: 1034228464    时间: 2021-10-12 18:46
python实现遗传算法易懂5 v* G1 e3 Q( Z

作者: lifekokool    时间: 2022-1-17 16:05
可能我有点笨吧,看了之后还是不知道该怎么应用某个问题+ R7 C3 C! m) Y2 L

作者: 738391227    时间: 2022-2-19 16:36
0000000000000000000000000. g9 v1 R9 i& Y. z/ a1 Y4 D0 |

作者: 852952290    时间: 2022-8-10 20:25
111111111111111111: |, Y# w3 i+ D( E5 U

作者: 2275929388    时间: 2022-10-9 14:14
遗传退货怎么都看不懂
* E  }- E1 D0 h* m8 v
作者: wwyx。    时间: 2022-10-9 18:28
赞赞赞赞
+ `/ C" _6 I% e8 k, U0 P8 u
作者: 2275929388    时间: 2022-10-10 09:08
566666666666666666666
" D) Z, V4 i" g6 Z; O9 Y
作者: 2580684929    时间: 2022-10-12 23:19
牛蛙,最近在看这个' O; E" Q& R* B( j





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