遗传算法单点交叉python代码
时间: 2023-11-04 14:59:00 浏览: 39
def single_point_crossover(parent1, parent2):
crossover_point = random.randint(0, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 示例使用
parent1 = [9, 3, 5, 4, 6, 0, 2, 1, 7, 8]
parent2 = [1, 4, 0, 2, 7, 8, 6, 9, 5, 3]
child1, child2 = single_point_crossover(parent1, parent2)
print(child1)
print(child2)
相关问题
遗传算法单点交叉操作python代码
以下是一个使用单点交叉操作的遗传算法的简单示例代码:
```python
import numpy as np
def single_point_crossover(parent1, parent2):
# 选择交叉点
crossover_point = np.random.randint(1, len(parent1))
# 生成两个子代个体
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2
# 示例使用的父代个体
parent1 = np.array([1, 2, 3, 4, 5])
parent2 = np.array([6, 7, 8, 9, 10])
# 执行单点交叉操作
child1, child2 = single_point_crossover(parent1, parent2)
# 输出结果
print("Parent 1:", parent1)
print("Parent 2:", parent2)
print("Child 1:", child1)
print("Child 2:", child2)
```
在这个示例代码中,`single_point_crossover` 函数实现了单点交叉操作。它接收两个父代个体 `parent1` 和 `parent2`,然后在一个随机选择的交叉点将两个个体进行切割,并生成两个子代个体 `child1` 和 `child2`。
在示例中,父代个体 `parent1` 是 `[1, 2, 3, 4, 5]`,父代个体 `parent2` 是 `[6, 7, 8, 9, 10]`。通过调用 `single_point_crossover` 函数,进行单点交叉操作,生成了两个子代个体 `child1` 和 `child2`。
最后,输出了父代和子代个体的值。注意,单点交叉操作将父代个体在交叉点处进行切割,并将部分基因从一个父代个体传递给子代个体,从而实现了遗传算法中的交叉操作。
遗传算法求解纳什均衡点的python代码
遗传算法可以用于求解纳什均衡点,以下是一个简单的Python代码示例:
```python
import random
# 设置博弈的参数
num_players = 2
num_strategies = 3
max_iterations = 100
population_size = 50
mutation_rate = 0.1
crossover_rate = 0.5
# 定义博弈矩阵
game_matrix = [[(1, 1), (-1, 2)],
[(2, -1), (0, 0)],
[(0, 0), (-1, -1)]]
# 定义个体编码方式
def encode_strategy(strategy):
return ''.join(str(s) for s in strategy)
def decode_strategy(encoded_strategy):
return [int(s) for s in encoded_strategy]
# 定义适应度函数
def fitness_function(strategy):
total_payoff = [0] * num_players
for i in range(num_players):
player_strategy = decode_strategy(strategy[i])
for j in range(num_strategies):
opponent_strategy = decode_strategy(strategy[(i + 1) % num_players])
payoff = game_matrix[player_strategy][opponent_strategy][i]
total_payoff[i] += payoff
return sum(total_payoff)
# 定义选择函数
def selection(population):
fitness_scores = [fitness_function(strategy) for strategy in population]
total_fitness = sum(fitness_scores)
probabilities = [fitness / total_fitness for fitness in fitness_scores]
selected_indices = random.choices(range(population_size), weights=probabilities, k=population_size)
return [population[i] for i in selected_indices]
# 定义交叉函数
def crossover(parent1, parent2):
if random.random() < crossover_rate:
crossover_point = random.randint(1, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
else:
return parent1, parent2
# 定义变异函数
def mutation(child):
mutated_child = ''
for bit in child:
if random.random() < mutation_rate:
mutated_child += '0' if bit == '1' else '1'
else:
mutated_child += bit
return mutated_child
# 初始化种群
population = [''.join(str(random.randint(0, 1)) for _ in range(num_strategies)) for _ in range(population_size)]
# 迭代
for iteration in range(max_iterations):
# 选择
selected_population = selection(population)
# 交叉
children = []
for i in range(0, population_size, 2):
child1, child2 = crossover(selected_population[i], selected_population[i+1])
children.append(mutation(child1))
children.append(mutation(child2))
# 替换
population = children
# 输出结果
fitness_scores = [fitness_function(strategy) for strategy in population]
best_strategy_index = fitness_scores.index(max(fitness_scores))
best_strategy = decode_strategy(population[best_strategy_index])
print('Best strategy:', best_strategy)
```
上述代码中,我们定义了一个2人3策略的博弈矩阵,然后使用遗传算法求解纳什均衡点。在适应度函数中,我们计算了每个个体的总收益,并以此作为适应度的度量。在选择函数中,我们使用轮盘赌选择法选择下一代种群。在交叉函数中,我们使用单点交叉法进行交叉操作。在变异函数中,我们使用随机位翻转法进行变异操作。最后,我们输出了得到的最优策略。