I am trying to implement Stochastic Universal Sampling, which works like this:
Let F be the sum of the fitness values of all chromosomes in the population.
Let N be the number of parents to select.
- Compute the distance P between successive points: P = F/N.
- Generate a random number between 0 and P as the starting point for the ruler. The ruler has N equally spaced points, each P distance apart.
- Assign each chromosome a range equal in length to its fitness and a starting point that is after the end point of the previous chromosome (e.g. first chromosome 01.53, 2nd chromosome 1.54-2.26, 3rd chromosome 2.27-3.42, etc).
- Select the chromosomes whose range contains a marker (note that a chromosome may have 2 markers in which case it is chosen twice).
I have implemented some part of this functionality but it is giving error
fitness_probSort = sorted(fitness_prob, key=attrgetter(fit_attr), reverse=True)
AttributeError: 'int' object has no attribute 'fitness'.
I am facing issue while implementing 5 and 6th step.
selection.py
def stochasticUniversalSampling(self, N, fit_attr="fitness"):
fitnessResults = {}
fitness_prob = {}
for i in range(0, len(self.population)):
fitnessResults[i] = self.population[i].getFitness()
fitness_prob[i] = 1 / fitnessResults[i]
fitness_probSort = sorted(fitness_prob, key=attrgetter(fit_attr), reverse=True)
print(fitness_probSort)
point_distance = 1 / N
start_point = random.uniform(0, point_distance)
points = [start_point + i * point_distance for i in range(N)]
chosen = []
for p in points:
i = 0
sum_ = getattr(fitness_probSort[i], fit_attr).values[0]
while sum_ < p:
i += 1
sum_ += getattr(fitness_probSort[i], fit_attr).values[0]
chosen.append(fitness_probSort[i])
return chosen