Skip to content
TheChatArchiveThe Chat Archive
grok-3-preview-02-24· xAIHugging Face LMArena Human Preference 140K

Code a python program that implements machine learning and natural selection.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o4-mini-2025-04-16’s answer.
  1. User

    Code a python program that implements machine learning and natural selection.

  2. Assistant

    Here's a Python program that implements a simple genetic algorithm (a form of machine learning inspired by natural selection) to solve a basic optimization problem. In this example, we'll try to evolve a string of characters to match a target phrase through natural selection principles.

    import random
    import string
    import time
    
    class GeneticAlgorithm:
        def __init__(self, target, population_size, mutation_rate):
            self.target = target
            self.population_size = population_size
            self.mutation_rate = mutation_rate
            self.population = []
            self.generation = 1
            self.best_fitness = 0
            self.best_solution = ""
            
        def create_individual(self):
            """Create a random string of the same length as target"""
            return ''.join(random.choice(string.ascii_letters + ' ') 
                          for _ in range(len(self.target)))
        
        def initialize_population(self):
            """Create initial random population"""
            self.population = [self.create_individual() 
                             for _ in range(self.population_size)]
        
        def calculate_fitness(self, individual):
            """Calculate fitness score (how similar to target)"""
            score = 0
            for i in range(len(self.target)):
                if individual[i] == self.target[i]:
                    score += 1
            return score / len(self.target)
        
        def select_parent(self):
            """Select a parent using tournament selection"""
            tournament_size = 3
            tournament = random.sample(self.population, tournament_size)
            return max(tournament, key=self.calculate_fitness)
        
        def crossover(self, parent1, parent2):
            """Create child by combining parents"""
            crossover_point = random.randint(0, len(self.target))
            child = parent1[:crossover_point] + parent2[crossover_point:]
            return child
        
        def mutate(self, individual):
            """Randomly mutate characters based on mutation rate"""
            individual_list = list(individual)
            for i in range(len(individual_list)):
                if random.random() < self.mutation_rate:
                    individual_list[i] = random.choice(string.ascii_letters + ' ')
            return ''.join(individual_list)
        
        def evolve(self):
            """Run one generation of evolution"""
            # Create new population
            new_population = []
            
            # Keep track of best solution
            for individual in self.population:
                fitness = self.calculate_fitness(individual)
                if fitness > self.best_fitness:
                    self.best_fitness = fitness
                    self.best_solution = individual
            
            # Create new generation
            for _ in range(self.population_size):
                # Select parents
                parent1 = self.select_parent()
                parent2 = self.select_parent()
                
                # Create child through crossover
                child = self.crossover(parent1, parent2)
                
                # Apply mutation
                child = self.mutate(child)
                
                new_population.append(child)
            
            self.population = new_population
            self.generation += 1
        
        def run(self, max_generations=1000):
            """Run the genetic algorithm until solution is found or max generations reached"""
            self.initialize_population()
            
            while self.best_fitness < 1.0 and self.generation <= max_generations:
                self.evolve()
                
                # Print progress every 100 generations
                if self.generation % 100 == 0:
                    print(f"Generation {self.generation}")
                    print(f"Best solution: {self.best_solution}")
                    print(f"Best fitness: {self.best_fitness:.2f}")
                    print("-" * 50)
                
                # If perfect solution found, break early
                if self.best_fitness == 1.0:
                    break
            
            # Print final results
            print("\nFinal Results:")
            print(f"Target: {self.target}")
            print(f"Best solution: {self.best_solution}")
            print(f"Generations: {self.generation}")
            print(f"Fitness: {self.best_fitness:.2f}")
    
    def main():
        # Parameters
        target_phrase = "Hello World"
        population_size = 100
        mutation_rate = 0.01
        
        print("Genetic Algorithm Starting...")
        print(f"Target phrase: {target_phrase}")
        print(f"Population size: {population_size}")
        print(f"Mutation rate: {mutation_rate}")
        print("=" * 50)
        
        # Create and run genetic algorithm
        ga = GeneticAlgorithm(target_phrase, population_size, mutation_rate)
        start_time = time.time()
        ga.run()
        end_time = time.time()
        
        print(f"\nTime taken: {end_time - start_time:.2f} seconds")
    
    if __name__ == "__main__":
        main()
    

    This program implements a genetic algorithm with the following components:

    1. Key Concepts:

      • Population: A group of potential solutions
      • Fitness: How good a solution is (how close to the target)
      • Selection: Choosing better solutions as parents
      • Crossover: Combining parents to create children
      • Mutation: Random changes to maintain diversity
    2. How it Works:

      • Starts with a random population of strings
      • Evaluates fitness (how many characters match the target)
      • Selects better solutions as parents
      • Creates new solutions through crossover and mutation
      • Repeats until the target is found or max generations reached
    3. Features:

      • Tournament selection for parent selection
      • Single-point crossover
      • Random mutation
      • Progress tracking
      • Performance metrics
    4. Output: The program will show:

      • Progress every 100 generations
      • Best solution found so far
      • Fitness score
      • Final results including generations taken and time elapsed

    To use the program:

    1. Run it as is to evolve toward "Hello World"
    2. Modify the target_phrase in main() to evolve toward a different string
    3. Adjust population_size and mutation_rate to experiment with different parameters

    Example modifications you could try:

    # Try a different target
    target_phrase = "Machine Learning"
    
    # Try different parameters
    population_size = 200
    mutation_rate = 0.02
    

    This is a simplified example of genetic algorithms, but it demonstrates the core principles of natural selection in machine learning:

    • Survival of the fittest (selection)
    • Genetic inheritance (crossover)
    • Random variation (mutation)
    • Evolution over generations

    The program can be extended to solve more complex problems by modifying the fitness function and representation of individuals.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.