|
| 1 | +import random |
| 2 | +import matplotlib.pyplot as plt |
| 3 | + |
| 4 | +""" |
| 5 | +This program uses a genetic algorithm to solve the 0/1 Knapsack problem. |
| 6 | +In the Knapsack problem, you are given a set of items, each with a value and a weight, |
| 7 | +and a knapsack with a weight limit. The goal is to select a combination of items |
| 8 | +to maximize the total value without exceeding the weight limit. |
| 9 | +This genetic algorithm iteratively evolves a population of candidate solutions to find the best combination. |
| 10 | +
|
| 11 | +Knapsack Problem Parameters: |
| 12 | +- weight_limit: The weight limit of the knapsack. |
| 13 | +- item_list: A list of items, where each item is represented as (value, weight). |
| 14 | +
|
| 15 | +Genetic Algorithm Parameters: |
| 16 | +- population_size: The size of the population. |
| 17 | +- max_generations: The maximum number of generations to run. |
| 18 | +- mutation_rate: The probability of mutation for each gene in the chromosome. |
| 19 | +- chromosome_length: The number of genes in each chromosome. |
| 20 | +""" |
| 21 | + |
| 22 | +# Knapsack Problem Parameters |
| 23 | +weight_limit = 56 |
| 24 | +item_list = [(17, 1), (78, 20), (56, 34), (2, 15), (34, 21), (3, 10)] # (value, weight) |
| 25 | + |
| 26 | +# Genetic Algorithm Parameters |
| 27 | +population_size = 100 |
| 28 | +max_generations = 300 |
| 29 | +mutation_rate = 0.5 |
| 30 | +chromosome_length = len(item_list) |
| 31 | + |
| 32 | + |
| 33 | +def initialize_population(): |
| 34 | + # Initialize the population with random chromosomes |
| 35 | + population = [] |
| 36 | + for _ in range(population_size): |
| 37 | + chromosome = [random.randint(0, 1) for _ in range(chromosome_length)] |
| 38 | + population.append(chromosome) |
| 39 | + return population |
| 40 | + |
| 41 | + |
| 42 | +def calculate_fitness(chromosome): |
| 43 | + # Calculate the fitness of a chromosome based on its value and weight |
| 44 | + total_value = 0 |
| 45 | + total_weight = 0 |
| 46 | + for gene, item in zip(chromosome, item_list): |
| 47 | + if gene == 1: |
| 48 | + total_value += item[0] |
| 49 | + total_weight += item[1] |
| 50 | + if total_weight > weight_limit: |
| 51 | + return 0 # Violates weight constraint |
| 52 | + return total_value |
| 53 | + |
| 54 | + |
| 55 | +def selection(population): |
| 56 | + # Select individuals from the population based on their fitness |
| 57 | + selected = [] |
| 58 | + total_fitness = sum(calculate_fitness(chromosome) for chromosome in population) |
| 59 | + for _ in range(population_size): |
| 60 | + r = random.uniform(0, total_fitness) |
| 61 | + cumulative_fitness = 0 |
| 62 | + for chromosome in population: |
| 63 | + cumulative_fitness += calculate_fitness(chromosome) |
| 64 | + if cumulative_fitness >= r: |
| 65 | + selected.append(chromosome) |
| 66 | + break |
| 67 | + return selected |
| 68 | + |
| 69 | + |
| 70 | +def crossover(parent1, parent2): |
| 71 | + # Perform one-point crossover to create two children |
| 72 | + crossover_point = random.randint(1, chromosome_length - 1) |
| 73 | + child1 = parent1[:crossover_point] + parent2[crossover_point:] |
| 74 | + child2 = parent2[:crossover_point] + parent1[crossover_point:] |
| 75 | + return child1, child2 |
| 76 | + |
| 77 | + |
| 78 | +def mutation(chromosome): |
| 79 | + # Apply mutation to a chromosome with a given probability |
| 80 | + mutated_chromosome = chromosome[:] |
| 81 | + for i in range(chromosome_length): |
| 82 | + if random.random() < mutation_rate: |
| 83 | + mutated_chromosome[i] = 1 - mutated_chromosome[i] |
| 84 | + return mutated_chromosome |
| 85 | + |
| 86 | + |
| 87 | +def genetic_algorithm(): |
| 88 | + # Main genetic algorithm loop |
| 89 | + population = initialize_population() |
| 90 | + fitness_history = [] |
| 91 | + for generation in range(max_generations): |
| 92 | + population = selection(population) |
| 93 | + new_population = [] |
| 94 | + while len(new_population) < population_size: |
| 95 | + parent1 = random.choice(population) |
| 96 | + parent2 = random.choice(population) |
| 97 | + child1, child2 = crossover(parent1, parent2) |
| 98 | + mutated_child1 = mutation(child1) |
| 99 | + mutated_child2 = mutation(child2) |
| 100 | + new_population.extend([mutated_child1, mutated_child2]) |
| 101 | + |
| 102 | + best_fit = max(calculate_fitness(chromosome) for chromosome in new_population) |
| 103 | + fitness_history.append(best_fit) |
| 104 | + |
| 105 | + population = new_population |
| 106 | + |
| 107 | + best_chromosome = max(population, key=calculate_fitness) |
| 108 | + best_fitness = calculate_fitness(best_chromosome) |
| 109 | + |
| 110 | + return best_chromosome, best_fitness, fitness_history |
| 111 | + |
| 112 | + |
| 113 | +# Run the genetic algorithm and print the result |
| 114 | +best_solution, best_fitness_value, fitness_history = genetic_algorithm() |
| 115 | +print("Best Solution:", best_solution) |
| 116 | +print("Best Fitness Value:", best_fitness_value) |
| 117 | + |
| 118 | +# Plot fitness history |
| 119 | +plt.plot(fitness_history) |
| 120 | +plt.title('Fitness History') |
| 121 | +plt.xlabel('Generation') |
| 122 | +plt.ylabel('Fitness') |
| 123 | +plt.show() |
0 commit comments