国际象棋皇后可以越过其他棋子吗(如何让8个皇后在国际象棋棋盘上和谐相处)(2)
def fitness_function(individual): value = 0 for i in range(7): for j in range(i 1,8,1): if individual[i] != individual[j]: x_distance = np.abs(individual[j] - individual[i]) y_distance = j - i if x_distance != y_distance: value = 1 return value
Softmax function 用于把顺应度函数转化为概率漫衍
def softmax(input): input = np.array(input, dtype=np.float) input = np.exp(input) output = input / input.sum() return output
Mutation 随机变异
def mutation(individual, prob=0.1): p = np.random.rand(8) individual[p>prob] = np.random.choice(range(8), 8)[p>prob] return individual
GA函数Genetic Algorithm
def GA(size = 4): #默认种群巨细为4,可以多试几个,结果纷歧样 size = size num_generation = 0 population = [] for i in range(size): population.append(np.random.choice(range(8), 8)) while (True): print("Generation : ", num_generation) fitness_list = [] selection = [] for individual in population: fitness_value = fitness_function(individual) if fitness_value == 28: print("Find Target!") print(individual) return individual fitness_list.append(fitness_value) print(fitness_list) print() #Selection is Here天然选择在这里 prob = softmax(fitness_list) select_id = np.random.choice(range(size), size, replace=True, p=prob) for idx in select_id: selection.append(population[idx]) num_pair = int(size/2) position = np.random.choice(range(1,7,1), num_pair, replace=True) #Crossover is Here基因片断的交错交流在这里 for i in range(0, size, 2): start = position[int(i/2)] tempa = copy.deepcopy(selection[i][start:]) tempb = copy.deepcopy(selection[i 1][start:]) selection[i][start:] = tempb selection[i 1][start:] = tempa #Mutation is Here变异在这里 for i in range(size): selection[i] = copy.deepcopy(mutation(selection[i], prob=0.8)) population = selection num_generation = 1
来看当作果吧
配置初始种群数目为4
Queen = GA(size = 4)
前4代的种群内4个个另外顺应度
后四代种群内4个个另外顺应度
我猜你应该发明白后四代种群的顺应度要高于前四代,声名父代顺应度更好的状态和有利的突变会或许率转达给子代。在第2071子代最后找到了满意前提的八皇后的解
你猜有几多种...
要问有几多种安排要领,我本身通过变动种群巨细和随机数,找到了几十种。高斯以为有76种方案。1854年在柏林的象棋杂志上差异的作者颁发了40种差异的解。
虽然不可是办理八皇后的
遗传算法在最优化题目上有普及的影响,如电路机关和功课车调治题目。今朝,还不清晰遗传算法的吸引力是源自它们的机能,照旧源自它们身世进化理论。许多研究事变正在举办中,说明在什么环境下行使遗传算法可以或许到达好的结果
日本新干线N700系列车
参考资料
Artificial Intelligence : A Modern Approach
https://baike.baidu.com/item/遗传算法/838140?fr=aladdin
(责任编辑:admin)