After more than half a year, now it's the next semester. When I think of this matter, I'll fill the pit
Without much to say, go directly to the python code of a genetic algorithm (reproduced according to the GA code in the teacher's PlatEMO framework. Please see the specific matlab code PlatEMO
I use cupy here. Cupy is equivalent to the upgraded version of numpy, which will speed up the operation between two ndarray s. Please see the specific usage Official documents , which is essentially different from numpy, only some data types are different.
from math import floor import cupy as cp import time class GA: def __init__(self,population,epochs): # Enter many individuals, i.e. populations self.population = population self.epochs = epochs def solve(self): rank = [] idx = 0 for i in range(self.epochs): matingPool = self.TournamentSelection(2,self.population.objs()) print("--------------The first{}Generation mating pool---------------".format(i+1)) print(matingPool) pop = [] for j in matingPool: pop.append(self.population.idvs[j]) offSpring = self.operator(pop) popu = self.population.idvs + offSpring rank.append(self.sort(popu)) self.population.idvs = rank[idx] idx += 1 print("The first{}Generation optimal network loss by{:.4f}".format(i+1,self.population.idvs[0].obj)) return rank def sort(self,pop): res = [] while len(res)<self.population.num: min = 100000000 idx = 0 for j in range(len(pop)): if pop[j].obj<min: min = pop[j].obj idx = j res.append(pop[idx]) pop.remove(pop[idx]) return res def TournamentSelection(self,K,objs): # k-ary League selection algorithm returns the best subscript array l = objs[:] l.sort() p = [[np.random.randint(0,len(l)).tolist() for m in range(K)] for n in range(len(l))] best = [] for i in p: min = i[0] for j in i: if j==min: continue if l[j] < l[min]: min = j best.append(min) return best def operator(self,pop): a = time.time() p1 = pop[0:floor(len(pop)/2)] p2 = pop[floor(len(pop)/2):floor(len(pop)/2)*2] for i in range(len(p1)): if p1[i]==p2[i]: continue if np.random.rand()<0.6: # Crossover rate 0.6 k = np.random.permutation(len(p1[0].w))[:floor(len(p1[0].w)*0.6)] t1 = p1[i] t2 = p2[i] t1.w[k],t2.w[k] = t2.w[k].copy(),t1.w[k].copy() p1[i],p2[i] = t1.copy(),t2.copy() b = time.time() print("CrossUseTime:{:.2f}s".format(b-a)) off = p1+p2 for i in range(len(off)): if np.random.rand()<0.2: # The variation rate was 0.2 # print("BeforMute obj:{:.4f}".format(off[i].obj)) m = np.random.permutation(len(off[0].w))[:floor(len(off[0].w)*0.02)] tmp = off[i] tmp.w[m] = -tmp.w[m].copy() off[i] = tmp.copy() # print("AfterMute obj:{:.4f}".format(off[i].obj)) print("MuteUseTime:{:.2f}s".format(time.time()-b)) return off
The crossover I use here is to simulate binary crossover SBX, and the mutation is for binary (- 1,1). The whole code is relatively simple, not as complete as that written in PlatEMO.
what? You asked me how Population and Individual wrote it?
This should be written according to the specific problem. After all, there is basically no change in the algorithm, only the data.
Then I'll give you a simple code for Population and Individual
Population
from Individual import Individual class population: def __init__(self,N): self.num = N self.idvs = [] for i in range(N): x = Randomly generated parameters idv = Individual() self.idvs.append(idv) print('individual{}The target value for is:{:.4f}'.format(i,idv.obj)) def objs(self): res = [] for i in self.idvs: res.append(i.obj) return res
Individual
import cupy as cp def LossF(**args): obj = args[0]+args[1]+... return obj class Individual: def __init__(self,**args): self.x = args self.obj = LossF(self.x) def copy(self): new = Individual(self.x) return new
It should be fairly easy to understand. I simplified many complex structures and directly extracted the most essential framework.
Digression:
Although I have read dozens of papers so far, I still don't have any innovative ideas. I feel that what I can think of has been done, and I can't think of what others haven't done. It's getting more and more difficult to engage in scientific research now. If we don't develop new fields, we really can't get out of the pit of involution.
To tell the truth, there are fewer and fewer fields that can be developed in the computer direction. The later you go to graduate school, the more difficult it is to innovate, and even issue a thesis graduation is a problem. Hundreds of thousands of graduate students graduate every year, and hundreds of thousands of papers have to be published every year. The later they enter the Bureau, the harder it is to produce results.
However, people must have dreams. After all, life without dream support is a blank, which will only become more and more boring. Maybe one day I can have a whim and come up with a new idea?