1.导入所需要的库
import numpy as np
import matplotlib.pyplot as plt
2.初始化
#初始化种群,popsize代表种群个数,n代表基因长度,
def init(popsize,n):
population=[]
for i in range(popsize):
pop=''
for j in range(n):
pop=pop+str(np.random.randint(0,2))
population.append(pop)
return population
3.计算fitness
#计算种群中重量和效益
def computeFitness(population,weight,profit):
total_weight = []
total_profit = []
for pop in population:
weight_temp = 0
profit_temp = 0
for index in range(len(pop)):
if pop[index] == '1':
weight_temp += int(weight[index])
profit_temp += int(profit[index])
total_weight.append(weight_temp)
total_profit.append(profit_temp)
return total_weight,total_profit
#计算单个个体
def computesingle(single,profit):
profit_temp = 0
for index in range(len(single)):
if single[index] == '1':
profit_temp += int(profit[index])
return profit_temp
4.筛选
#筛选符合条件的
def select(population,weight_limit,total_weight,total_profit):
w_temp = []
p_temp = []
pop_temp = []
for weight in total_weight:
out = total_weight.index(weight)
if weight <= weight_limit:
w_temp.append(total_weight[out])
p_temp.append(total_profit[out])
pop_temp.append(population[out])
return pop_temp,w_temp,p_temp
4.轮盘赌选择
def roulettewheel(s_pop,total_profit):
p =[0]
temp = 0
sum_profit = sum(total_profit)
for i in range(len(total_profit)):
unit = total_profit[i]/sum_profit
p.append(temp+unit)
temp += unit
new_population = []
i0 = 0
while i0 < popsize:
select_p = np.random.uniform()
for i in range(len(s_pop)):
if select_p