Fitness problem in genetic algorithm using python
I created code that uses genetic algorithms.But there is a problem with def fitness and def max_fitness. I want to make a function that returns a small value of the result value from def fitness part, but I do not know how to do it.
It seems to be using it incorrectly because I can not understand @staticmethod and @property. I really appreciate it if you let me know.
def random_chunk(li, min_chunk=1, max_chunk=9):
# random.shuffle(li)
it = iter(li)
while True:
nxt = list(islice(it,randint(min_chunk,max_chunk)))
if nxt:
yield nxt
else:
break
def countChar(char, list):
return [k.count(char) for k in list]
def sumOfList2(v_list,we):
result =
for item in v_list:
log2 = math.log(float(item + 1), 2)
MC_k = we * item * (2*log2)
result.append(MC_k)
return sum(result)
def rand(x,y): return int(uniform(x,y))
mutation_probability = 10
DNA_CNT = 5
dd = [['1,2', 1], ['1,3', 0],['1,4', 1],['1,5', 0],['2,3', 1],['2,4', 0], ['2,5', 1],['3,4', 0],['3,5', 1], ['4,5', 1]]
cha = dict(dd)
Data= cha.values()
# print Data
# print cha
class Generation:
cnt = 0
def __init__(self,dna_list):
Generation.cnt += 1
self.generation_level = Generation.cnt
self.DNA_list = dna_list
self.select_list = self.make_select_list()
def __repr__(self):
return "<Generation level %d>" % self.generation_level
def make_select_list(self):
tmp_list = list()
for dna in self.DNA_list:
tmp_list += [dna for _ in xrange(int(dna.fitness))]
return tmp_list
def make_child(self):
if rand(0, self.fitness * mutation_probability) == 0:
return DNA([random.randint(0,len(Data)) for _ in xrange(len(Data))])
parents = tuple(self.select_list[rand(0, len(self.select_list))] for _ in range(2))
gene_data = list()
gene_len = len(parents[0].gene_data)
switch_point = (rand(1, gene_len //2), rand(gene_len //2 ,gene_len))
parent = parents[0]
for _ in xrange(gene_len):
gene_data.append(parent.gene_data[_])
if i in switch_point:
try:
parent = parents[parents.index(parent) +1]
except IndexError:
parent = parents[0]
dna = DNA(gene_data)
return dna
def evolution(self):
print("Start Evolution Generation level %d" % Generation.cnt)
dna_list = [self.best for _ in xrange(DNA_CNT)]
dna_list += [self.make_child() for _ in xrange(len(self.DNA_list) - len(dna_list))]
return Generation(dna_list)
@property
def fitness(self):
# print mean([dna.fitness for dna in self.DNA_list])
return mean([dna.fitness for dna in self.DNA_list])
@property
def best(self):
return sorted(self.DNA_list, key=lambda x: x.fitness, reverse=True)[0]
class DNA:
def __init__(self, gene_data =None):
if gene_data is None:
self.gene_data = [rand(min(Data), max(Data) + 1) for _ in range(len(Data))]
else:
self.gene_data = gene_data
def __repr__(self):
return "<Gene %s | %d>" % ("_".join(str(x) for x in self.gene_data), self.fitness)
@staticmethod
def max_fitness():
if max(Data) < 2 :
return len(Data) * max(Data)
else:
return len(Data) * (max(Data) // 2)
@property
def fitness(self):
sum_ =
k=
sum1 = 0
minn = 1
score = DNA.max_fitness()
# print self.gene_data
aa = self.gene_data.count(1)
if aa == 6:
a = (list(random_chunk(self.gene_data)))
# print a
for _ in a:
if len(_) == minn and _[0] == 1:
out_1 = sumOfList2(_, 0.3)
sum1 += out_1
find_0 = countChar(0,a)
in_0 = sumOfList2(find_0, 0.3)
result = sum1 + in_0
print result
# print chrom
# print aa
# if aa == score:
# return aa
return score
if __name__ == '__main__':
Generations = list()
Generations.append(Generation([DNA() for _ in range(100)]))
i = 0
while True:
try:
next_generation = Generations[i].evolution()
Generations.append(next_generation)
print("Fitness: %d" % next_generation.fitness)
print("Best DNA: %s" % next_generation.best)
if next_generation.fitness >= DNA.fitness():
break
i = i+1
except KeyboardInterrupt:
break
print("Last Generation's Best DNA: %s" % Generations[-1].best)
# visualization(Generations)
python python-2.7
add a comment |
I created code that uses genetic algorithms.But there is a problem with def fitness and def max_fitness. I want to make a function that returns a small value of the result value from def fitness part, but I do not know how to do it.
It seems to be using it incorrectly because I can not understand @staticmethod and @property. I really appreciate it if you let me know.
def random_chunk(li, min_chunk=1, max_chunk=9):
# random.shuffle(li)
it = iter(li)
while True:
nxt = list(islice(it,randint(min_chunk,max_chunk)))
if nxt:
yield nxt
else:
break
def countChar(char, list):
return [k.count(char) for k in list]
def sumOfList2(v_list,we):
result =
for item in v_list:
log2 = math.log(float(item + 1), 2)
MC_k = we * item * (2*log2)
result.append(MC_k)
return sum(result)
def rand(x,y): return int(uniform(x,y))
mutation_probability = 10
DNA_CNT = 5
dd = [['1,2', 1], ['1,3', 0],['1,4', 1],['1,5', 0],['2,3', 1],['2,4', 0], ['2,5', 1],['3,4', 0],['3,5', 1], ['4,5', 1]]
cha = dict(dd)
Data= cha.values()
# print Data
# print cha
class Generation:
cnt = 0
def __init__(self,dna_list):
Generation.cnt += 1
self.generation_level = Generation.cnt
self.DNA_list = dna_list
self.select_list = self.make_select_list()
def __repr__(self):
return "<Generation level %d>" % self.generation_level
def make_select_list(self):
tmp_list = list()
for dna in self.DNA_list:
tmp_list += [dna for _ in xrange(int(dna.fitness))]
return tmp_list
def make_child(self):
if rand(0, self.fitness * mutation_probability) == 0:
return DNA([random.randint(0,len(Data)) for _ in xrange(len(Data))])
parents = tuple(self.select_list[rand(0, len(self.select_list))] for _ in range(2))
gene_data = list()
gene_len = len(parents[0].gene_data)
switch_point = (rand(1, gene_len //2), rand(gene_len //2 ,gene_len))
parent = parents[0]
for _ in xrange(gene_len):
gene_data.append(parent.gene_data[_])
if i in switch_point:
try:
parent = parents[parents.index(parent) +1]
except IndexError:
parent = parents[0]
dna = DNA(gene_data)
return dna
def evolution(self):
print("Start Evolution Generation level %d" % Generation.cnt)
dna_list = [self.best for _ in xrange(DNA_CNT)]
dna_list += [self.make_child() for _ in xrange(len(self.DNA_list) - len(dna_list))]
return Generation(dna_list)
@property
def fitness(self):
# print mean([dna.fitness for dna in self.DNA_list])
return mean([dna.fitness for dna in self.DNA_list])
@property
def best(self):
return sorted(self.DNA_list, key=lambda x: x.fitness, reverse=True)[0]
class DNA:
def __init__(self, gene_data =None):
if gene_data is None:
self.gene_data = [rand(min(Data), max(Data) + 1) for _ in range(len(Data))]
else:
self.gene_data = gene_data
def __repr__(self):
return "<Gene %s | %d>" % ("_".join(str(x) for x in self.gene_data), self.fitness)
@staticmethod
def max_fitness():
if max(Data) < 2 :
return len(Data) * max(Data)
else:
return len(Data) * (max(Data) // 2)
@property
def fitness(self):
sum_ =
k=
sum1 = 0
minn = 1
score = DNA.max_fitness()
# print self.gene_data
aa = self.gene_data.count(1)
if aa == 6:
a = (list(random_chunk(self.gene_data)))
# print a
for _ in a:
if len(_) == minn and _[0] == 1:
out_1 = sumOfList2(_, 0.3)
sum1 += out_1
find_0 = countChar(0,a)
in_0 = sumOfList2(find_0, 0.3)
result = sum1 + in_0
print result
# print chrom
# print aa
# if aa == score:
# return aa
return score
if __name__ == '__main__':
Generations = list()
Generations.append(Generation([DNA() for _ in range(100)]))
i = 0
while True:
try:
next_generation = Generations[i].evolution()
Generations.append(next_generation)
print("Fitness: %d" % next_generation.fitness)
print("Best DNA: %s" % next_generation.best)
if next_generation.fitness >= DNA.fitness():
break
i = i+1
except KeyboardInterrupt:
break
print("Last Generation's Best DNA: %s" % Generations[-1].best)
# visualization(Generations)
python python-2.7
add a comment |
I created code that uses genetic algorithms.But there is a problem with def fitness and def max_fitness. I want to make a function that returns a small value of the result value from def fitness part, but I do not know how to do it.
It seems to be using it incorrectly because I can not understand @staticmethod and @property. I really appreciate it if you let me know.
def random_chunk(li, min_chunk=1, max_chunk=9):
# random.shuffle(li)
it = iter(li)
while True:
nxt = list(islice(it,randint(min_chunk,max_chunk)))
if nxt:
yield nxt
else:
break
def countChar(char, list):
return [k.count(char) for k in list]
def sumOfList2(v_list,we):
result =
for item in v_list:
log2 = math.log(float(item + 1), 2)
MC_k = we * item * (2*log2)
result.append(MC_k)
return sum(result)
def rand(x,y): return int(uniform(x,y))
mutation_probability = 10
DNA_CNT = 5
dd = [['1,2', 1], ['1,3', 0],['1,4', 1],['1,5', 0],['2,3', 1],['2,4', 0], ['2,5', 1],['3,4', 0],['3,5', 1], ['4,5', 1]]
cha = dict(dd)
Data= cha.values()
# print Data
# print cha
class Generation:
cnt = 0
def __init__(self,dna_list):
Generation.cnt += 1
self.generation_level = Generation.cnt
self.DNA_list = dna_list
self.select_list = self.make_select_list()
def __repr__(self):
return "<Generation level %d>" % self.generation_level
def make_select_list(self):
tmp_list = list()
for dna in self.DNA_list:
tmp_list += [dna for _ in xrange(int(dna.fitness))]
return tmp_list
def make_child(self):
if rand(0, self.fitness * mutation_probability) == 0:
return DNA([random.randint(0,len(Data)) for _ in xrange(len(Data))])
parents = tuple(self.select_list[rand(0, len(self.select_list))] for _ in range(2))
gene_data = list()
gene_len = len(parents[0].gene_data)
switch_point = (rand(1, gene_len //2), rand(gene_len //2 ,gene_len))
parent = parents[0]
for _ in xrange(gene_len):
gene_data.append(parent.gene_data[_])
if i in switch_point:
try:
parent = parents[parents.index(parent) +1]
except IndexError:
parent = parents[0]
dna = DNA(gene_data)
return dna
def evolution(self):
print("Start Evolution Generation level %d" % Generation.cnt)
dna_list = [self.best for _ in xrange(DNA_CNT)]
dna_list += [self.make_child() for _ in xrange(len(self.DNA_list) - len(dna_list))]
return Generation(dna_list)
@property
def fitness(self):
# print mean([dna.fitness for dna in self.DNA_list])
return mean([dna.fitness for dna in self.DNA_list])
@property
def best(self):
return sorted(self.DNA_list, key=lambda x: x.fitness, reverse=True)[0]
class DNA:
def __init__(self, gene_data =None):
if gene_data is None:
self.gene_data = [rand(min(Data), max(Data) + 1) for _ in range(len(Data))]
else:
self.gene_data = gene_data
def __repr__(self):
return "<Gene %s | %d>" % ("_".join(str(x) for x in self.gene_data), self.fitness)
@staticmethod
def max_fitness():
if max(Data) < 2 :
return len(Data) * max(Data)
else:
return len(Data) * (max(Data) // 2)
@property
def fitness(self):
sum_ =
k=
sum1 = 0
minn = 1
score = DNA.max_fitness()
# print self.gene_data
aa = self.gene_data.count(1)
if aa == 6:
a = (list(random_chunk(self.gene_data)))
# print a
for _ in a:
if len(_) == minn and _[0] == 1:
out_1 = sumOfList2(_, 0.3)
sum1 += out_1
find_0 = countChar(0,a)
in_0 = sumOfList2(find_0, 0.3)
result = sum1 + in_0
print result
# print chrom
# print aa
# if aa == score:
# return aa
return score
if __name__ == '__main__':
Generations = list()
Generations.append(Generation([DNA() for _ in range(100)]))
i = 0
while True:
try:
next_generation = Generations[i].evolution()
Generations.append(next_generation)
print("Fitness: %d" % next_generation.fitness)
print("Best DNA: %s" % next_generation.best)
if next_generation.fitness >= DNA.fitness():
break
i = i+1
except KeyboardInterrupt:
break
print("Last Generation's Best DNA: %s" % Generations[-1].best)
# visualization(Generations)
python python-2.7
I created code that uses genetic algorithms.But there is a problem with def fitness and def max_fitness. I want to make a function that returns a small value of the result value from def fitness part, but I do not know how to do it.
It seems to be using it incorrectly because I can not understand @staticmethod and @property. I really appreciate it if you let me know.
def random_chunk(li, min_chunk=1, max_chunk=9):
# random.shuffle(li)
it = iter(li)
while True:
nxt = list(islice(it,randint(min_chunk,max_chunk)))
if nxt:
yield nxt
else:
break
def countChar(char, list):
return [k.count(char) for k in list]
def sumOfList2(v_list,we):
result =
for item in v_list:
log2 = math.log(float(item + 1), 2)
MC_k = we * item * (2*log2)
result.append(MC_k)
return sum(result)
def rand(x,y): return int(uniform(x,y))
mutation_probability = 10
DNA_CNT = 5
dd = [['1,2', 1], ['1,3', 0],['1,4', 1],['1,5', 0],['2,3', 1],['2,4', 0], ['2,5', 1],['3,4', 0],['3,5', 1], ['4,5', 1]]
cha = dict(dd)
Data= cha.values()
# print Data
# print cha
class Generation:
cnt = 0
def __init__(self,dna_list):
Generation.cnt += 1
self.generation_level = Generation.cnt
self.DNA_list = dna_list
self.select_list = self.make_select_list()
def __repr__(self):
return "<Generation level %d>" % self.generation_level
def make_select_list(self):
tmp_list = list()
for dna in self.DNA_list:
tmp_list += [dna for _ in xrange(int(dna.fitness))]
return tmp_list
def make_child(self):
if rand(0, self.fitness * mutation_probability) == 0:
return DNA([random.randint(0,len(Data)) for _ in xrange(len(Data))])
parents = tuple(self.select_list[rand(0, len(self.select_list))] for _ in range(2))
gene_data = list()
gene_len = len(parents[0].gene_data)
switch_point = (rand(1, gene_len //2), rand(gene_len //2 ,gene_len))
parent = parents[0]
for _ in xrange(gene_len):
gene_data.append(parent.gene_data[_])
if i in switch_point:
try:
parent = parents[parents.index(parent) +1]
except IndexError:
parent = parents[0]
dna = DNA(gene_data)
return dna
def evolution(self):
print("Start Evolution Generation level %d" % Generation.cnt)
dna_list = [self.best for _ in xrange(DNA_CNT)]
dna_list += [self.make_child() for _ in xrange(len(self.DNA_list) - len(dna_list))]
return Generation(dna_list)
@property
def fitness(self):
# print mean([dna.fitness for dna in self.DNA_list])
return mean([dna.fitness for dna in self.DNA_list])
@property
def best(self):
return sorted(self.DNA_list, key=lambda x: x.fitness, reverse=True)[0]
class DNA:
def __init__(self, gene_data =None):
if gene_data is None:
self.gene_data = [rand(min(Data), max(Data) + 1) for _ in range(len(Data))]
else:
self.gene_data = gene_data
def __repr__(self):
return "<Gene %s | %d>" % ("_".join(str(x) for x in self.gene_data), self.fitness)
@staticmethod
def max_fitness():
if max(Data) < 2 :
return len(Data) * max(Data)
else:
return len(Data) * (max(Data) // 2)
@property
def fitness(self):
sum_ =
k=
sum1 = 0
minn = 1
score = DNA.max_fitness()
# print self.gene_data
aa = self.gene_data.count(1)
if aa == 6:
a = (list(random_chunk(self.gene_data)))
# print a
for _ in a:
if len(_) == minn and _[0] == 1:
out_1 = sumOfList2(_, 0.3)
sum1 += out_1
find_0 = countChar(0,a)
in_0 = sumOfList2(find_0, 0.3)
result = sum1 + in_0
print result
# print chrom
# print aa
# if aa == score:
# return aa
return score
if __name__ == '__main__':
Generations = list()
Generations.append(Generation([DNA() for _ in range(100)]))
i = 0
while True:
try:
next_generation = Generations[i].evolution()
Generations.append(next_generation)
print("Fitness: %d" % next_generation.fitness)
print("Best DNA: %s" % next_generation.best)
if next_generation.fitness >= DNA.fitness():
break
i = i+1
except KeyboardInterrupt:
break
print("Last Generation's Best DNA: %s" % Generations[-1].best)
# visualization(Generations)
python python-2.7
python python-2.7
asked Nov 24 '18 at 10:47
johnyjohny
11
11
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457350%2ffitness-problem-in-genetic-algorithm-using-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457350%2ffitness-problem-in-genetic-algorithm-using-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown