Answer To: its an artificial intelligence homework
Abr Writing answered on Mar 22 2021
tsp.py
#!/usr/bin/env python
# coding: utf-8
# # Traveling Salesman Problem
# In[1]:
from random import sample, random
from pandas import DataFrame
from numpy import array
import operator
class Tour:
def __init__(self, dists, perm):
self.dists = dists
self.n = len(dists)
if perm is None:
self.perm = list(range(self.n))
else:
self.perm = perm
self.fitness = 0
self.population = []
def tourValue(self):
value = 0
for index, city in enumerate(self.perm):
value += self.dists[city][self.perm[(index+1)%self.n]]
return value
def printTour(self):
print(' <- '.join([str(x+1) for x in self.perm]) +
' <- ' +
str(self.perm[0]+1))
def tourFitness(self):
if self.fitness == 0:
self.fitness = 1 / self.tourValue()
return self.fitness
class Genetic:
def __init__(self,
initialTour,
mutationRate = 0.01,
populationSize = 1000,
eliteSize = 20,
generations = 500):
self.n = initialTour.n
self.dists = initialTour.dists
self.populationSize = populationSize
self.eliteSize = eliteSize
self.mutationRate = mutationRate
self.population = [
sample(list(range(self.n)), self.n) for i in range(populationSize)
]
def updatePopulationSize(self, populationSize):
self.populationSize = populationSize
self.population = [
sample(list(range(self.n)), self.n) for i in range(populationSize)
]
def rankPopulation(self, populationSize = 10):
results = dict()
for i in range(self.populationSize):
results[i] = Tour(self.dists, self.population[i]).tourFitness()
return sorted(
results.items(),
key = operator.itemgetter(1),
reverse = True
)
def selection(self):
results = []
populationRank = self.rankPopulation()
ranks = DataFrame(array(populationRank), columns=["index","fitness"])
ranks['cumSum'] = ranks.fitness.cumsum()
ranks['cumperc'] = 100*ranks.cumSum/ranks.fitness.sum()
for i in range(0, self.eliteSize):
results.append(populationRank[i][0])
for i in range(0, self.populationSize - self.eliteSize):
pick = 100*random()
for i in range(self.populationSize):
if pick <= ranks.iat[i,3]:
results.append(populationRank[i][0])
break
return results
def matingPool(self, selectionResults):
pool = []
for i in range(0, len(selectionResults)):
index = selectionResults[i]
pool.append(self.population[index])
return pool
def breed(self, p1, p2):
child = []
childP1 = []
childP2 = []
genA = int(random() * len(p1))
genB = int(random() * len(p1))
startGen = min(genA, genB)
endGen = max(genA, genB)
for i in range(startGen, endGen):
childP1.append(p1[i])
childP2 = [item for item in p2 if item not in childP1]
return childP1 + childP2
def breedPopulation(self, matingpool):
children = []
length = len(matingpool) -...