import numpy genes=2 chromosomes=10 mattingPoolSize=6 offspringSize=chromosomes-mattingPoolSize lb=-5 ub=5 populationSize=(chromosomes,genes) generations=3 population=numpy.random.uniform(lb,ub,populationSize) for generation in range(generations): print(("Generation:",generation+1)) fitness=numpy.sum(population*population,axis=1) print("\npopulation") print(population) print("\nfitness calculation") print(fitness) parents=numpy.empty((mattingPoolSize,population.shape[1])) for p in range(mattingPoolSize): fittestIndex=numpy.where(fitness==numpy.max(fitness)) fittestIndex=fittestIndex[0][0] parents[p,:]=population[fittestIndex,:] fitness[fittestIndex]=-1 print("\nParents:") print(parents) offspring=numpy.empty((offspringSize,population.shape[1])) for k in range(offspringSize): crossoverPoint=numpy.random.randint(0,genes) parent1Index=k%parents.shape[0] parent2Index=(k+1)%parents.shape[0] offspring[k,0:crossoverPoint]=parents[parent1Index,0:crossoverPoint] offspring[k,crossoverPoint:]=parents[parent2Index,crossoverPoint:] print("\nOffspring after crossover:") print(offspring) for index in range(offspring.shape[0]): randomIndex=numpy.random.randint(1,genes) randomValue=numpy.random.uniform(lb,ub,1) offspring[index,randomIndex]=offspring[index,randomIndex]+randomValue print("\noffspring after Mutation") print(offspring) population[0:parents.shape[0],:]=parents population[parents.shape[0]:,:]=offspring print("\nNew population for next generation:") print(population) fitness=numpy.sum(population*population,axis=1) fittestIndex=numpy.where(fitness==numpy.max(fitness)) fittestIndex=fittestIndex[0][0] fittestInd=population[fittestIndex,:] bestFitness=fitness[fittestIndex] print("\nBest Individual:") print(fittestInd) print("\nBest Individual's Fitness:") print(bestFitness)