1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| def CCDE(pop_size, generation, length, model, image, target_label, eps, batch_size, gradient): generation_save = np.zeros((10000,)) problem = Problem(model, image, target_label, eps, batch_size) subpop = [np.random.uniform(-1, 1, size=(pop_size, length)) for _ in range(2)] n_subpop = len(subpop) if (not (gradient is None)): for i in range(n_subpop): subpop[i][0] = np.reshape(np.sign(gradient), (length)) max_eval = pop_size * generation eval_count = 0 fitness, fit = np.zeros((n_subpop,)), np.zeros((n_subpop,)) for i in range(n_subpop): fitness[i], fit[i] = problem.evaluate(subpop[i]) eval_count += pop_size count = 0 fitmin = np.zeros((n_subpop,)) for i in range(n_subpop): fitmin[i]=np.min(fitness) generation_save[count] = fitmin F = 0.5 if (len(np.where(fitness[0] == 0)[0]) == 0): while (eval_count < max_eval): count += 1 for i in range(n_subpop): off = mating(subpop[i],F) off_fitness , off_fit = problem.evaluate(off) eval_count += pop_size subpop[i] ,fitness[i] ,fit[i] = select(subpop[i],fitness[i],fit[i], off, off_fitness, off_fit) subpop[i], fitness[i], fit[i] = complement(fit[i], subpop[i], fitness[i], problem) fitmin[i] = np.min(fitness[i]) subpop[0] ,fitness[0] ,fit[0] = select(subpop[0],fitness[0],fit[0],subpop[1],fitness[1],fit[1]) subpop[0], fitness[0], fit[0] = complement(fit[0], subpop[0], fitness[0], problem) generation_save[count] = np.min(fitmin[0]) if (len(np.where(fitness[0] == 0)[0]) != 0): break if (len(np.where(fitness[0] == 0)[0]) != 0): return subpop[0][np.where(fitness[0] == 0)[0][0]], eval_count, generation_save[:count + 1] else: return subpop[0][0], eval_count/100, generation_save[:count + 1]
|