資源簡介
非常簡單的Python蟻群算法,智能算法入門,歡迎下載!
代碼片段和文件信息
‘‘‘
Created?on?Apr?3?2015
@author:?Ke?Wang
@see:?Artificial?Bee?Colony?Algorithm?ABCA?蟻群算法
‘‘‘
import?random
import?copy
import?numpy?as?np
import?time
class?Source():
????‘‘‘
????Location?Pattern?
????Near?Location
????Distance
????Fitness
????‘‘‘
????
????def?__init__(self?**sourceInfo):
????????self.setPara(**sourceInfo)
????????self.fitness?=?self.getFitness(self.pattern)
????#//__init__
????
????def?setPara(self?**sourceInfo):
????????self.sourceInfo?=?sourceInfo
????????self.limit?=?sourceInfo[‘limit‘]
????????self.pattern?=?sourceInfo[‘pattern‘]
????????self.randLocation?=?sourceInfo[‘randLocation‘]?#function
????????self.getDistance?=?sourceInfo[‘getDistance‘]?#function
????????
????????if?‘location‘?not?in?sourceInfo:
????????????self.location?=?self.randLocation()
????????else:
????????????self.location?=?sourceInfo[‘location‘]
????#//setPara
????????
????def?getFitness(self?source):
????????self.fitness?=?1.0/self.getDistance(self.patternself.location)
????????return?self.fitness
????#//getFitness
????
????def?compareSource(self?newSource):
????????return?self.fitness?-?newSource.fitness
????#//compareSource
????????
????######?create?Near?Source?######
????def?createNearSource(self?anotherBeelocation):
????????theSourceInfo?=?copy.deepcopy(self.sourceInfo)
????????theSourceInfo[‘location‘]?=?self.location[:]
????????for?i?in?range(len(self.location)):
????????????theSourceInfo[‘location‘][i]?=?self.location[i]?+?random.uniform(-11)*(self.location[i]-anotherBeelocation[i])
????????
????????nearSource?=?Source(**theSourceInfo)
????????
????????return?nearSource
????#//createNearSource
???
class?Bee():
????‘‘‘
????Leader?Bee
????
????next?action:
????????~1?recruit?and?back?current?source
????????~2?give?up?current?source?to?explore
????????~3?don‘t?recruit?and?go?back?current?source
????????
????‘‘‘
????
????def?__init__(self?abc?**para):
????????
????????self.source?=?Source(**abc.sourceInfo)
????????self.setPara(**para)
????????self.abc?=?abc
????????
????????self.state?=?self.actionChoice()
????#//__init__
????
????def?setPara(self?**para):
????????if?‘fitnessThreshold‘?not?in?para:?self.fitnessThreshold?=?0
????????else:?self.fitnessThreshold?=?para[‘fitnessThreshold‘]
????#//setPara
????
????
????def?actionChoice(self):
????????
????????if?self.source.fitness?????????????self.isRecruit?=?1
????????????self.exploreNewSource()
????????????self.source.limit-=1
????????????return?2?#if?source?is?ran?out?or?not?fit?then?give?up?this?and?explore?new?one
????????
????????if?random.random()?0:?###?parameter?that?leader?bee?don‘t?recruit?and?back?source
????????????self.isRecruit?=?0
????????????self.source.limit?-=1
????????????return?3
????????else:
????????????self.isRecruit?=?1
????????????self.source.limit?-=1
????????????return?1
????#//actionChoice
????
?
- 上一篇:Python爬蟲教程千萬別錯過
- 下一篇:樹莓派目標跟蹤代碼python
評論
共有 條評論