from deap import tools,base,creator
import random
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
saidai=30 ##1にする数
def makegene(container):
hako=[0]*200
sel=random.sample(range(len(hako)),saidai)
for h in sel:
hako[h]=1
return container(hako)
toolbox.register("individual", makegene, creator.Individual)
#toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 200)
ind=toolbox.individual()
print(ind)
[0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ind.count(1)
30
上記では、1が30個に固定されている。この数をランダムに1から30個までにする場合。
from deap import tools,base,creator
import random
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
saidai=30 ##1から最大数saidaiまでにする
def makegene(container):
hako=[0]*200
sel=random.sample(range(len(hako)),random.randint(1,saidai))
for h in sel:
hako[h]=1
return container(hako)
toolbox.register("individual", makegene, creator.Individual)
ind=toolbox.individual()
print(ind)
print(ind.count(1))