good day,
I try to run the following code gen.py in python 2.5 in order to resolve the STP with genetic algorithm, but i find an error:
Traceback (most recent call last):
File "C:\Python25\gen.py", line 55, in <module>
class population:
File "C:\Python25\gen.py", line 61, in population
for v in range(self.nombre_initial_population):
NameError: name 'self' is not defined
the code: gen.py
please any one help me. -
# -*- coding: cp1252 -*-
-
import random, sys, os, time
-
class individu:
-
def __init__ (self,nombre_genes,random=-1):
-
self.genes = []
-
self.nombre_genes = nombre_genes
-
if random == -1 : self.random ()
-
"""
-
random : initialise aleatoirement les genes
-
"""
-
def random (self):
-
self.genes = []
-
f = range(0,self.nombre_genes)
-
for v in range(self.nombre_genes):
-
val = random.choice (f)
-
f.remove (val)
-
self.genes.append (val)
-
"""
-
evaluation : compare l'individu avec un tableau d'autres individus
-
retourne le nombre d'individus auquel l'individu self est superieur et de meilleure
-
qualité
-
"""
-
def evalutation (self,autres_individus,distances):
-
valeur_individu = 0
-
for v in autres_individus:
-
if self.compare(v,distances) > 0 : valeur_individu = valeur_individu + 1
-
self.valeur_individu = valeur_individu
-
return valeur_individu
-
"""
-
compare : compare l'individu self avec un autre individu
-
retourne un nombre positif s'il est superieur
-
un nombre negatif s'il est inferieur
-
le nombre 0 s'il est égal
-
"""
-
def calcul_distance (self,distance):
-
a = self.genes[0]
-
dist = 0
-
for b in self.genes[1:]:
-
min=0
-
max=0
-
if a > b :
-
min = b
-
max = a
-
else :
-
min = a
-
max = b
-
dist = dist + (distance[min])[max-min-1]
-
a = b
-
self.distance = dist
-
return dist
-
def compare (self,individu,distance):
-
individu.calcul_distance (distance)
-
self.calcul_distance (distance)
-
return self.distance - individu.distance
-
class population:
-
def __init__ (self,nombre_genes,nombre_initial_population=50):
-
self.nombre_genes = nombre_genes
-
self.distances = [[]] * nombre_genes
-
self.individus = []
-
self.nombre_initial_population = nombre_initial_population
-
for v in range(self.nombre_initial_population):
-
self.individus.append (individu(nombre_genes))
-
"""
-
selection : methode de selection des meilleurs N individus
-
"""
-
def selection (self , N=-1):
-
if N == -1 : N = len(self.individus)
-
for v in self.individus:
-
v.evalutation (self.individus,self.distances)
-
self.individus.sort (lambda a,b : a.valeur_individu - b.valeur_individu)
-
if N <= len(self.individus) : self.individus = self.individus[0:N]
-
"""
-
croisement : selectionne deux individus et croise leur gênes pour en creer de nouveaux
-
"""
-
def croisement_deux (self , i1 , i2):
-
i = individu (self.nombre_genes)
-
l = len(i1.genes)
-
a = l / 2
-
p2 = i2.genes[a:l]
-
p1 = i1.genes[0:a]
-
choices = range(0,l)
-
for v in p1:
-
try:choices.remove (v)
-
except : pass
-
for v in p2:
-
try : choices.remove (v)
-
except : pass
-
idc = 0
-
for id in range(len(p2)):
-
if p2[id] in p1:
-
p2[id] = choices[idc]
-
idc = idc + 1
-
i.genes = p1 + p2
-
return i
-
""" croise tous les individus entre eux"""
-
def croisement_all (self):
-
new = []
-
for v1 in range(len(self.individus)):
-
for v2 in range(v1,len(self.individus)):
-
new.append ( self.croisement_deux (self.individus[v1] , self.individus[v2]))
-
self.individus = self.individus + new
-
""" croise nombre_croisement individus aleatoires entre eux """
-
def croisement_nombre (self , nombre_croisement):
-
new = []
-
for r in range(nombre_croisement):
-
v1 = random.randint (0 , len(self.individus)-1)
-
v2 = random.randint (0 , len(self.individus)-1)
-
new.append (self.croisement_deux (self.individus[v1] , self.individus[v2]) )
-
self.individus = self.individus + new
-
if __name__ == "__main__" :
-
p = population (10,50) # population de 50 individus puis on initialise les distances
-
p.distances[0] = [2,3,4,5,6,7,8,9,10 ] # distance de la premiere ville avec la 2eme , 3eme , ... , 10eme
-
p.distances[1] = [11,12,13,14,15,16,17,18 ] # distance de la deuxieme ville avec la 3eme , 4eme , ... ,10eme
-
p.distances[2] = [19,20,21,22,23,24,25] #etc...
-
p.distances[3] = [26,27,28,29,30,31]
-
p.distances[4] = [32,33,34,35,36]
-
p.distances[5] = [37,38,39 ,40]
-
p.distances[6] = [41,42,43]
-
p.distances[7] = [44,45]
-
p.distances[8] = [46] # distance de la 9eme ville avec la 10eme ville
-
"""
-
10 generations
-
a chaque fois fait 100 croisements
-
et selectionne les 10 premiers
-
"""
-
for i in range(10):
-
p.croisement_nombre (100)
-
p.selection (10)
-
for v in p.individus:
-
print v.genes,v.calcul_distance (p.distances)
-
-
3 1805
You need that line to be properly space line 61 to be on the same level as the previous lines.
hay,
I have a an other errorin the run of the code gen.py
the error:
Traceback (most recent call last):
File "C:\Python25\gen.py", line 111, in <module>
p = population (10,50) # population de 50 individus puis on initialise les distances
File "C:\Python25\gen.py", line 62, in __init__
self.individus.append (individu(nombre_genes))
File "C:\Python25\gen.py", line 7, in __init__
if random == -1 : self.random () -
# -*- coding: cp1252 -*-
-
import random, sys, os, time
-
class individu:
-
def __init__ (self,nombre_genes,random=-1):
-
self.genes = []
-
self.nombre_genes = nombre_genes
-
if random == -1 : self.random ()
-
"""
-
random : initialise aleatoirement les genes
-
"""
-
def random (self):
-
self.genes = []
-
f = range(0,self.nombre_genes)
-
for v in range(self.nombre_genes):
-
val = random.choice (f)
-
f.remove (val)
-
self.genes.append (val)
-
"""
-
evaluation : compare l'individu avec un tableau d'autres individus
-
retourne le nombre d'individus auquel l'individu self est superieur et de meilleure
-
qualité
-
"""
-
def evalutation (self,autres_individus,distances):
-
valeur_individu = 0
-
for v in autres_individus:
-
if self.compare(v,distances) > 0 : valeur_individu = valeur_individu + 1
-
self.valeur_individu = valeur_individu
-
return valeur_individu
-
"""
-
compare : compare l'individu self avec un autre individu
-
retourne un nombre positif s'il est superieur
-
un nombre negatif s'il est inferieur
-
le nombre 0 s'il est égal
-
"""
-
def calcul_distance (self,distance):
-
a = self.genes[0]
-
dist = 0
-
for b in self.genes[1:]:
-
min=0
-
max=0
-
if a > b :
-
min = b
-
max = a
-
else :
-
min = a
-
max = b
-
dist = dist + (distance[min])[max-min-1]
-
a = b
-
self.distance = dist
-
return dist
-
def compare (self,individu,distance):
-
individu.calcul_distance (distance)
-
self.calcul_distance (distance)
-
return self.distance - individu.distance
-
class population:
-
def __init__ (self,nombre_genes,nombre_initial_population=50):
-
self.nombre_genes = nombre_genes
-
self.distances = [[]] * nombre_genes
-
self.individus = []
-
self.nombre_initial_population = nombre_initial_population
-
for v in range(self.nombre_initial_population):
-
self.individus.append (individu(nombre_genes))
-
"""
-
selection : methode de selection des meilleurs N individus
-
"""
-
def selection (self , N=-1):
-
if N == -1 : N = len(self.individus)
-
for v in self.individus:
-
v.evalutation (self.individus,self.distances)
-
self.individus.sort (lambda a,b : a.valeur_individu - b.valeur_individu)
-
if N <= len(self.individus) : self.individus = self.individus[0:N]
-
"""
-
croisement : selectionne deux individus et croise leur gênes pour en creer de nouveaux
-
"""
-
def croisement_deux (self , i1 , i2):
-
i = individu (self.nombre_genes)
-
l = len(i1.genes)
-
a = l / 2
-
p2 = i2.genes[a:l]
-
p1 = i1.genes[0:a]
-
choices = range(0,l)
-
for v in p1:
-
try:choices.remove (v)
-
except : pass
-
for v in p2:
-
try : choices.remove (v)
-
except : pass
-
idc = 0
-
for id in range(len(p2)):
-
if p2[id] in p1:
-
p2[id] = choices[idc]
-
idc = idc + 1
-
i.genes = p1 + p2
-
return i
-
""" croise tous les individus entre eux"""
-
def croisement_all (self):
-
new = []
-
for v1 in range(len(self.individus)):
-
for v2 in range(v1,len(self.individus)):
-
new.append ( self.croisement_deux (self.individus[v1] , self.individus[v2]))
-
self.individus = self.individus + new
-
""" croise nombre_croisement individus aleatoires entre eux """
-
def croisement_nombre (self , nombre_croisement):
-
new = []
-
for r in range(nombre_croisement):
-
v1 = random.randint (0 , len(self.individus)-1)
-
v2 = random.randint (0 , len(self.individus)-1)
-
new.append (self.croisement_deux (self.individus[v1] , self.individus[v2]) )
-
self.individus = self.individus + new
-
if __name__ == "__main__" :
-
p = population (10,50) # population de 50 individus puis on initialise les distances
-
p.distances[0] = [2,3,4,5,6,7,8,9,10 ] # distance de la premiere ville avec la 2eme , 3eme , ... , 10eme
-
p.distances[1] = [11,12,13,14,15,16,17,18 ] # distance de la deuxieme ville avec la 3eme , 4eme , ... ,10eme
-
p.distances[2] = [19,20,21,22,23,24,25] #etc...
-
p.distances[3] = [26,27,28,29,30,31]
-
p.distances[4] = [32,33,34,35,36]
-
p.distances[5] = [37,38,39 ,40]
-
p.distances[6] = [41,42,43]
-
p.distances[7] = [44,45]
-
p.distances[8] = [46] # distance de la 9eme ville avec la 10eme ville
-
"""
-
10 generations
-
a chaque fois fait 100 croisements
-
et selectionne les 10 premiers
-
"""
-
for i in range(10):
-
p.croisement_nombre (100)
-
p.selection (10)
-
for v in p.individus:
-
print v.genes,v.calcul_distance (p.distances)
-
-
Your code is not properly indented. The class has only one method (__init__) as it's the only indented one (with one space). So it's unable to see random as a member.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Chris McKeever |
last post by:
I am trying to modify the Mailman Python code to stop mapping
MIME-types and use the extension of the attachment instead. I am
pretty much clueless as to what I need to do here, but I think I have...
|
by: F. GEIGER |
last post by:
I've dev'ed a Python prototype of an app, that besides the internals making
it up has a gui. While test-driven dev'ing the app's internals in Python is
fun as usual, dev'ing the GUI is not so...
|
by: Robey Holderith |
last post by:
Does anybody know of a tool that can tell me all possible exceptions that
might occur in each line of code? What I'm hoping to find is something
like the following:
given all necessary python...
|
by: Hansan |
last post by:
Hi all, I hope you have time to help me out a little. My problem is that I
want to combine some python code I have made with some html templates, I
found a tutorial at dev shed:...
|
by: sushant.sirsikar |
last post by:
hi,
I am new to Python programming.I am not getting exactly pdb.Can
anyone tell me effective way to debug python code?
Please give me any example.
Looking for responce.
Thank You.
Sushant
|
by: mistral |
last post by:
Need compile python code, source is in html and starts with parameters:
#!/bin/sh -
"exec" "python" "-O" "$0" "$@"
I have installed ActivePython for windows.
|
by: kaens |
last post by:
Hey everyone, I'm relatively new to python - I actually picked it up
to see how quickly I could start building non-trivial apps with it.
Needless to say, I was quite pleased.
Anyhow, I'm...
|
by: Python Maniac |
last post by:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.
def scrambleLine(line):
s = ''
for c in line:
s += chr(ord(c) | 0x80)...
|
by: Marcin Krol |
last post by:
Right, I didn't realize before that Python interpreter has its own
signal handling routines.
Now I am able to handle signals in Python code, but it still barfs on exit:
import time
import...
|
by: Jalindar Gat |
last post by:
Hi all, I am new bee in Python programming...
I am trying to download web page using python code
code:
import urllib
# Get a file-like object for the Python Web site's home page.
f =...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |