用python写一个遗传算法
时间: 2024-05-24 21:04:43 浏览: 18
好的,下面是一个简单的遗传算法的 Python 实现。
首先,我们需要定义一个适应度函数来评估每个个体的适应性。这里我们用一个简单的函数,计算一个二进制数字中 1 的数量作为适应度函数。
```python
def fitness(individual):
return sum(individual)
```
然后,我们需要生成初始群体。这里我们使用随机生成二进制数的方式。
```python
import random
POPULATION_SIZE = 100
GENE_LENGTH = 10
population = []
for i in range(POPULATION_SIZE):
individual = [random.randint(0, 1) for j in range(GENE_LENGTH)]
population.append(individual)
```
接下来,我们需要进行选择、交叉和变异操作。这里我们采用轮盘赌选择、单点交叉和随机位变异。具体实现如下:
```python
def selection(population):
total_fitness = sum([fitness(individual) for individual in population])
probability = [fitness(individual) / total_fitness for individual in population]
return random.choices(population, weights=probability, k=2)
def crossover(parents):
crossover_point = random.randint(1, GENE_LENGTH - 1)
child1 = parents[0][:crossover_point] + parents[1][crossover_point:]
child2 = parents[1][:crossover_point] + parents[0][crossover_point:]
return child1, child2
def mutation(individual):
mutation_point = random.randint(0, GENE_LENGTH - 1)
individual[mutation_point] = 1 - individual[mutation_point]
return individual
```
最后,我们需要进行迭代,不断更新群体并选择最佳个体。这里我们采用了 100 次迭代。
```python
GENERATIONS = 100
for i in range(GENERATIONS):
# Calculate fitness
fitness_values = [fitness(individual) for individual in population]
# Select parents
parents = [selection(population) for j in range(POPULATION_SIZE // 2)]
# Crossover and mutation
offspring = []
for parents_pair in parents:
offspring_pair = crossover(parents_pair)
offspring_pair = [mutation(child) for child in offspring_pair]
offspring.extend(offspring_pair)
# Update population
population = offspring
# Select best individual and print fitness
best_individual = max(population, key=fitness)
print(f"Generation {i+1}: Best fitness = {fitness(best_individual)}")
```
这里我们每次迭代都选出最适应的个体并输出其适应度。你可以根据需要修改输出内容。
以上就是一个简单的遗传算法 Python 实现。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)