資源簡介
最基礎的遺傳算法,使用python實現。
代碼片段和文件信息
“““
????Genetic?algorithm
????-----------------
????Modified?date?:?2018/11/13??19:27
“““
#?import?libs
import?numpy?as?np
import?matplotlib.pyplot?as?plt
#?Constant?definition
MIN_VAL?=?[0]
MAX_VAL?=?[10]
#?Class?definition
class?GA():
????“““
????????GA?class
????“““
????def?__init__(self?pop_num=50?chromosome_len=20?pc=0.8?pm=0.1?iters=200?v_num=1):
????????“““
????????“““
????????self.pop_num?=?pop_num???????????????????????????????????#?Total?group?number
????????self.chromosome_len?=?chromosome_len?????????????????????#?Chromosome?length
????????self.pc?=?pc?????????????????????????????????????????????#?Cross?probability
????????self.pm?=?pm?????????????????????????????????????????????#?Mutation?probability
????????self.iters?=?iters???????????????????????????????????????#?Number?of?iterations
????????self.v_num?=?v_num???????????????????????????????????????#?Number?of?variables
????????self.optimal_solu?=?None?????????????????????????????????#?Optimal?solution
????????self.pop_size?=?np.zeros((self.pop_num?self.chromosome_len*self.v_num))???#?Population
????????self.trace?=?[]??????????????????????????????????????????#
????def?init_pops(self):
????????“““
????????????init_pops?function
????????????------------------
????????“““
????????for?i?in?range(self.pop_num):
????????????for?j?in?range(self.chromosome_len):
????????????????self.pop_size[i?j]?=?np.random.randint(02)
????def?fitness(self?x):
????????“““
????????????fitness?function
????????????----------------
????????????????Parameter:
????????????????????x?:?Variable?to?be?solved
????????????????Return?:
????????????????????fitval?:?Fitness?value
????????“““
????????#?objective?function?
????????fitval?=?x?+?10*np.sin(5*x)+?7*np.cos(4*x)
????????#?Return?value
????????return?fitval
????def?btod(self?b):
????????“““
????????????btod?function
????????????-------------
????????????????Parameter:
????????????????????b?;?Binary?number
????????????????Return:
????????????????????d?:?Decimal
????????“““
????????d?=?0
????????for?i?in?range(len(b)):
????????????d?=?d?+?b[i]*2**(len(b)-1-i)
????????return?d????????
????def?get_decimal(self?bins):
????????“““
????????????get_decimal?function
????????????--------------------
????????????????Parameter:
????????????????????bins???:?Binary?number?set
????????????????Return:
????????????????????vals_10:?Decimal?number?set
????????“““
????????#?2?to?10
????????x_10?=?np.zeros((self.pop_num?1))
????????k?=?0
????????for?x_2?in?bins:
????????????x_10[k]?=?self.btod(x_2)
????????????k?+=1
????????#?10?converts?to?the?specified?span
????????vals_10?=?np.zeros((self.pop_num?1))
????????for?i?in?range(self.pop_num):
????????????for?j?in?range(1):
????????????????vals_10[i]?=?MIN_VAL[j]?+?x_10[i]*((MAX_VAL[j]-MIN_VAL[j])/(2**self.chromosome_len-1))
????????#?Return?value
????????return?vals_10???
????
????def?cumsum(self?ps):
???
評論
共有 條評論