在遗传算法中选择父母

时间:2018-06-27 16:59:06

标签: python genetic-algorithm

我试图做到这一点,因此当我运行代码时,父母数组中的父母仅使用一次。我只是为了排除故障而缩短了数字。我希望程序从阵列中选择一种可能的组合。一旦选择了单个元素,我希望它不再可用。

我当前正在使用的代码:

#Importing the needed functions

import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
import random
from itertools import permutations as permutation


#Defining my mating function where I want each parent in the parent array to be only once and not repeat. 
def mating (parents):
    parent1 = 0 
    parent2 = 0
    parent1 = permutation(parents,2)
    parent2 = permutation(parents , 2)
    print ("parent1: ", list(parent1))
    print ("parent2: ", list(parent2))

#Function used to create my 4 parents and 3 genes
def generateRandom(population , m):
   Population = np.random.rand (population,m)   
   return(Population)

# main code where I am setting returns from the functions to other vairables to call later
for i in range(2):
    candidateSolution = generateRandom(4,3)
    print ("the solutions: ", candidateSolution)
    full_population = mating(candidateSolution

我现在得到的输出是一个排列,其中元素0用于元素1、2、3。

我想做的是将一个随机父级分配给父级1,将一个随机未使用的父级分配给父级2。我只想对每个父级使用一次。

我正在查看的一个主题表明我得到的是:Pair combinations of elements in dictionary without repetition

但是,他们希望将其放置在元素0被多次使用的位置。我希望只使用一次。

2 个答案:

答案 0 :(得分:1)

您可以在随机列表中选择已定义的项目,而不是在有序列表中选择唯一的随机组合。这样,您可以确定父母的唯一性,并保证繁殖的随机性。

Exiting main...

根据您的例程,它变成:

from random import shuffle
parents = [i for i in range(10)]
shuffle(parents)

n = len(parents)
couples = [(parents[i], parents[n-i-1]) for i in range(int(n/2))]

print(couples)
# an output obtained [(8, 7), (5, 2), (6, 9), (1, 0), (4, 3)]

答案 1 :(得分:0)

用于解决此问题的代码为:

for i in range (int(len(parents)/2)):
    parent1 = parents[i]
    parent2 = parents[-i-1]
    print ("Parent1: ", parent1)
    print ("parent2: ",parent2)

这适用于我的长度将是偶数的事实。