给出遗传算法的代码
时间: 2023-07-07 22:14:43 浏览: 69
好的,以下是一个简单的 Python 实现遗传算法求解带时间窗的旅行售货员问题的代码,供您参考:
```python
import random
class City:
def __init__(self, id, demand, tw):
self.id = id
self.demand = demand
self.tw = tw
class Individual:
def __init__(self, cities):
self.cities = cities
self.fitness = 0
def generate_individual(num_cities):
cities = []
for i in range(num_cities):
demand = random.randint(1, 10)
tw_start = random.randint(0, 4)
tw_end = tw_start + random.randint(1, 3)
cities.append(City(i, demand, (tw_start, tw_end)))
random.shuffle(cities)
return Individual(cities)
def calculate_fitness(individual, dist_matrix):
total_distance = 0
time = 0
for i in range(len(individual.cities)):
city1 = individual.cities[i]
city2 = individual.cities[(i+1)%len(individual.cities)]
total_distance += dist_matrix[city1.id][city2.id]
time += dist_matrix[city1.id][city2.id]
if time < city1.tw[0]:
time = city1.tw[0]
elif time > city1.tw[1]:
return 0
time += 1 # assuming 1 unit of time to serve each city's demand
if time > city2.tw[1]:
return 0
city2.demand -= min(city2.demand, time - city2.tw[0])
return total_distance
def select_parents(population):
fitness_values = [ind.fitness for ind in population]
total_fitness = sum(fitness_values)
probabilities = [f/total_fitness for f in fitness_values]
parents = []
for i in range(2):
r = random.random()
cumulative_prob = 0
for j in range(len(population)):
cumulative_prob += probabilities[j]
if r < cumulative_prob:
parents.append(population[j])
break
return parents
def crossover(parent1, parent2):
child_cities = [None] * len(parent1.cities)
start = random.randint(0, len(parent1.cities)-1)
end = random.randint(start, len(parent1.cities)-1)
for i in range(start, end+1):
child_cities[i] = parent1.cities[i]
for city in parent2.cities:
if city not in child_cities:
for i in range(len(child_cities)):
if child_cities[i] is None:
child_cities[i] = city
break
return Individual(child_cities)
def mutate(individual):
if random.random() < 0.1:
i1 = random.randint(0, len(individual.cities)-1)
i2 = random.randint(0, len(individual.cities)-1)
individual.cities[i1], individual.cities[i2] = individual.cities[i2], individual.cities[i1]
def genetic_algorithm(num_cities, dist_matrix, num_generations, pop_size):
population = [generate_individual(num_cities) for i in range(pop_size)]
for i in range(num_generations):
for individual in population:
individual.fitness = calculate_fitness(individual, dist_matrix)
population.sort(key=lambda x: x.fitness, reverse=True)
print(f"Generation {i+1}, Best fitness: {population[0].fitness}")
parents = select_parents(population)
child = crossover(parents[0], parents[1])
mutate(child)
population[-1] = child
return population[0]
```
其中,`City` 类表示一个城市,包含城市的需求量和时间窗信息;`Individual` 类表示一个个体,包含城市的排列和适应度值。
`generate_individual` 函数用于生成一个随机的个体,`calculate_fitness` 函数用于计算个体的适应度值,`select_parents` 函数用于选择父代,`crossover` 函数用于进行交叉操作,`mutate` 函数用于进行变异操作。
`genetic_algorithm` 函数是遗传算法的主函数,其中 `num_cities` 表示城市的数量,`dist_matrix` 表示城市间的距离矩阵,`num_generations` 表示迭代次数,`pop_size` 表示种群大小。该函数会输出每一代的最佳适应度值,最终返回最优个体。
阅读全文