please create a very simple genetic algorithm in python without any imported ML libraries. only math and numpy are allowed to be imported if neccessary. use a simple example sandwhich receipes and popularity.
Assistant
python
import random
import numpy as np
# Define the possible ingredients
ingredients = ["bread", "cheese", "ham", "tomato", "lettuce", "onion"]
# Define a function to generate a random sandwich recipe
def create_sandwich():
return [random.choice([0, 1]) for _ in range(len(ingredients))]
# Define a function to calculate the "popularity" of a sandwich
def evaluate_sandwich(sandwich):
# This is a very simple example, you can make it more complex
popularity = sum(sandwich) # More ingredients = more popular (for now)
return popularity
# Define the genetic algorithm parameters
population_size = 10
generations = 50
mutation_rate = 0.1
# Create the initial population
population = [create_sandwich() for _ in range(population_size)]
# Run the genetic algorithm
for generation in range(generations):
# Evaluate the fitness of each sandwich
fitness_scores = [evaluate_sandwich(sandwich) for sandwich in population]
# Select the best sandwiches for breeding
parents = random.choices(population, weights=fitness_scores, k=population_size)
# Create the next generation through crossover and mutation
new_population = []
for i in range(0, population_size, 2):
parent1 = parents[i]
parent2 = parents[i+1]
# Crossover: Combine the genes of the parents
crossover_point = random.randint(1, len(ingredients) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
# Mutation: Randomly change some genes
for j in range(len(ingredients)):
if random.random() < mutation_rate:
child1[j] = 1 - child1[j]
if random.random() < mutation_rate:
child2[j] = 1 - child2[j]
new_population.extend([child1, child2])
population = new_population
# Find the best sandwich in the final population
best_sandwich = population[np.argmax(fitness_scores)]
# Print the best sandwich recipe
print("Best Sandwich:")
for i, ingredient in enumerate(ingredients):
if best_sandwich[i] == 1:
print(ingredient)
Explanation:
Ingredients and Recipe Representation:
ingredients: A list of possible ingredients.
create_sandwich(): Generates a random sandwich recipe represented as a list of 0s and 1s, where 1 means the ingredient is included.
Fitness Function:
evaluate_sandwich(): A simple function that calculates the "popularity" of a sandwich. In this example, it just sums the number of ingredients (more ingredients = more popular). You can make this more complex based on taste preferences or other criteria.
Genetic Algorithm Parameters:
population_size: Number of sandwiches in each generation.
generations: Number of iterations of the algorithm.
mutation_rate: Probability of a gene (ingredient) being flipped (added or removed) during mutation.
Initialization:
Creates an initial population of random sandwich recipes.
Evolutionary Loop:
Evaluation: Calculates the fitness (popularity) of each sandwich in the population.
Selection: Chooses "parents" for the next generation based on their fitness scores (higher fitness = more likely to be selected).
Crossover: Combines the genes of two parents to create two offspring.
Mutation: Randomly changes some genes in the offspring to introduce variation.
New Population: The offspring become the new population for the next generation.
Finding the Best:
After all generations, the sandwich with the highest fitness score is considered the "best" sandwich.
Key Points:
This is a very basic example. Real-world genetic algorithms often have more sophisticated fitness functions, selection methods, and genetic operators.
The evaluate_sandwich() function is crucial and should be tailored to your specific problem and desired outcome.
Experiment with different parameters (population size, generations, mutation rate) to see how they affect the results.