import numpy as np
import matplotlib.pyplot as plt
values = np.array([
360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,
78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,
87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276,
312])
weights = np.array([
7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,
42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,
3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13])
capacity = 850
def greedy_knapsack_weight(weights, values, capacity):
"""Consider lighter items first; return a feasible binary solution."""
items = sorted(zip(weights, values, range(len(weights))))
solution = np.zeros(len(weights), dtype=int)
total_value, total_weight = 0, 0
for weight, value, index in items:
if total_weight + weight <= capacity:
solution[index] = 1
total_weight += weight
total_value += value
return solution, total_value, total_weight
def greedy_knapsack_value(weights, values, capacity):
"""Consider more valuable items first, skipping those that do not fit."""
items = sorted(zip(values, weights, range(len(weights))), reverse=True)
solution = np.zeros(len(weights), dtype=int)
total_value, total_weight = 0, 0
for value, weight, index in items:
if total_weight + weight <= capacity:
solution[index] = 1
total_weight += weight
total_value += value
return solution, total_value, total_weight
def greedy_knapsack_ratio(weights, values, capacity):
"""Consider value/weight ratios, taking positive-value free items first."""
ratios = np.divide(values, weights, out=np.full(len(weights), np.inf),
where=weights != 0)
items = sorted(zip(ratios, values, weights, range(len(weights))), reverse=True)
solution = np.zeros(len(weights), dtype=int)
total_value, total_weight = 0, 0
for ratio, value, weight, index in items:
if total_weight + weight <= capacity:
solution[index] = 1
total_weight += weight
total_value += value
return solution, total_value, total_weight
def initialize_population(pop_size, num_items, rng):
"""Generate random binary candidates; feasibility is assessed separately."""
return rng.integers(2, size=(pop_size, num_items))
def evaluate_fitness(population, weights, values, capacity, penalty_factor=10):
"""Score candidates for selection; a finite penalty does not enforce capacity."""
total_weights = population @ weights
total_values = population @ values
penalties = penalty_factor * np.maximum(0, total_weights - capacity)
return total_values - penalties
def roulette_selection(population, fitness, rng):
"""Sample parents with replacement, proportional to shifted fitness."""
adjusted_fitness = fitness - np.min(fitness) + 1e-6
probabilities = adjusted_fitness / np.sum(adjusted_fitness)
selected_indices = rng.choice(len(population), size=len(population),
replace=True, p=probabilities)
return population[selected_indices]
def tournament_selection(population, fitness, tournament_size, rng):
"""Select one winner per tournament; larger scores are better here."""
selected_indices = []
for _ in range(len(population)):
participants = rng.choice(len(population), tournament_size, replace=False)
winner = participants[np.argmax(fitness[participants])]
selected_indices.append(winner)
return population[selected_indices]
def single_point_crossover(parents, crossover_rate, rng):
"""Recombine binary parents, returning the same number of offspring."""
num_parents, num_genes = parents.shape
parents = parents[rng.permutation(num_parents)]
offspring = []
for i in range(0, num_parents, 2):
parent1 = parents[i]
parent2 = parents[(i + 1) % num_parents]
child1, child2 = parent1.copy(), parent2.copy()
if num_genes > 1 and rng.random() < crossover_rate:
point = rng.integers(1, num_genes)
child1[:point], child2[:point] = parent2[:point], parent1[:point]
offspring.extend((child1, child2))
return np.array(offspring[:num_parents])
def uniform_crossover(parents, crossover_rate, rng):
"""Choose independently which parent supplies each binary gene."""
num_parents, num_genes = parents.shape
parents = parents[rng.permutation(num_parents)]
offspring = []
for i in range(0, num_parents, 2):
parent1 = parents[i]
parent2 = parents[(i + 1) % num_parents]
child1, child2 = parent1.copy(), parent2.copy()
if rng.random() < crossover_rate:
mask = rng.integers(2, size=num_genes).astype(bool)
child1[mask], child2[mask] = parent2[mask], parent1[mask]
offspring.extend((child1, child2))
return np.array(offspring[:num_parents])
def mutation(offspring, mutation_rate, rng):
"""Flip each bit independently with the specified per-gene probability."""
mutation_matrix = rng.random(offspring.shape) < mutation_rate
offspring[mutation_matrix] = 1 - offspring[mutation_matrix]
return offspring
def elitism(population, fitness, elite_size):
"""Copy the highest-scoring individuals into the next population."""
if elite_size == 0:
return population[:0].copy()
elite_indices = np.argsort(fitness)[-elite_size:]
return population[elite_indices].copy()
def genetic_algorithm(weights, values, capacity, *, rng, pop_size=100,
num_generations=100, crossover_rate=0.8,
mutation_rate=0.05, elite_percent=0.02,
selection_type='roulette', tournament_size=3,
crossover_type='single_point', penalty_factor=10):
"""Run one binary GA and return its best feasible solution and fitness traces.
Histories contain generations 0 through num_generations. The population
budget is pop_size * (num_generations + 1) fitness evaluations. All item
values and weights are nonnegative; the empty knapsack is feasible.
"""
population = initialize_population(pop_size, len(weights), rng)
elite_size = int(pop_size * elite_percent)
best_solution = np.zeros(len(weights), dtype=int)
best_value, best_weight = 0, 0
average_fitness_history, best_fitness_history = [], []
for generation in range(num_generations + 1):
fitness = evaluate_fitness(population, weights, values, capacity,
penalty_factor)
average_fitness_history.append(float(np.mean(fitness)))
best_fitness_history.append(float(np.max(fitness)))
# Selection scores may favor overweight candidates. Keep a feasible
# incumbent by actual value, independently of the selection policy.
total_weights = population @ weights
total_values = population @ values
feasible_indices = np.flatnonzero(total_weights <= capacity)
if len(feasible_indices) > 0:
index = feasible_indices[np.argmax(total_values[feasible_indices])]
if total_values[index] > best_value:
best_solution = population[index].copy()
best_value = total_values[index]
best_weight = total_weights[index]
if generation == num_generations:
break # The final population has been evaluated and recorded.
elites = elitism(population, fitness, elite_size)
if selection_type == 'roulette':
parents = roulette_selection(population, fitness, rng)
elif selection_type == 'tournament':
parents = tournament_selection(population, fitness, tournament_size, rng)
else:
raise ValueError("Choose 'roulette' or 'tournament' selection.")
if crossover_type == 'single_point':
offspring = single_point_crossover(parents, crossover_rate, rng)
elif crossover_type == 'uniform':
offspring = uniform_crossover(parents, crossover_rate, rng)
else:
raise ValueError("Choose 'single_point' or 'uniform' crossover.")
offspring = mutation(offspring, mutation_rate, rng)
population = np.vstack((elites, offspring[:pop_size - elite_size]))
return (best_solution, best_value, best_weight,
average_fitness_history, best_fitness_history)
def plot_fitness_over_generations(avg_fitness_history, best_fitness_history):
"""Show selection scores, including generation 0 and the final population."""
generations = np.arange(len(avg_fitness_history))
plt.figure(figsize=(6, 5))
plt.plot(generations, avg_fitness_history, label='Mean selection fitness')
plt.plot(generations, best_fitness_history, label='Maximum selection fitness')
plt.xlabel('Generation')
plt.ylabel('Penalized fitness')
plt.title('Selection Fitness over Generations')
plt.legend()
plt.tight_layout()
plt.show()