def __init__(self, num_inputs, weights=None): '''ctor: if weights are not explicitly given, clamped random values are used.''' if weights is not None: # The extra weight is for the bias self.weights = weights[:] + [clamped_rand()] self.num_inputs = len(weights) + 1 else: self.weights = [clamped_rand() for i in xrange(num_inputs + 1)] self.num_inputs = num_inputs + 1
def mutate(self, genome): ''' mutates a chromosome, based on the mutation_rate by perturbing its weights by an amount not greater than max_perturbation. **This potentially modifies the argument passed and returns whether this mod took place.** ''' mutated = False for i in xrange(len(genome.weights)): if random() < settings.MUTATION_RATE: genome.weights[i] += (clamped_rand() * settings.MAX_PERTURBATION) mutated = True return mutated
def __init__(self, popsize, mutrate, crossrate, numweights): ''' Constructor ''' self._population_size = popsize self._mutation_rate = mutrate self._crossover_rate = crossrate self._chromo_length = numweights self._total_fitness = 0.0 self._generation_count = 0 self._fittest_genome = 0 self._best_fitness = 0.0 self._worst_fitness = INFINITY self._average_fitness = 0.0 self._population = [] for i in xrange(popsize): weights = [clamped_rand() for j in xrange(numweights)] self._population.append(Genome(weights, 0.0))