基于遗传算法的旅行销售员

时间:2017-09-26 19:55:08

标签: python algorithm genetic-algorithm traveling-salesman

我正在尝试使用python和遗传算法可视化和解决旅行销售人员的问题,我在youtube上关注Daniel Shiffman的编码挑战视频之一我不知道我是否允许在这里添加链接但这里是链接(https://www.youtube.com/watch?v=M3KTWnTrU_c&list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH&index=42

所以问题是,我的遗传算法没有进化。它刚刚停留在第一代。我想我无法编写创建下一代的代码,因为它应该是由于我对python缺乏了解,这里是代码:

 import pygame
import random
import numpy as np
import sys

size=width,height=500,500
bgColor = (0,0,0)
screen = pygame.display.set_mode(size)
vertexArray = []
fitness = []
population = []
pygame.display.set_caption("Finding the Shortest path with Genetich Algorithm")
bestEver=[]
bestDistance = 999999

def shuffle(vertexArray):
    np.random.shuffle(vertexArray)
def swap(a,i,j):
    temp = a[i]
    a[i]=a[j]
    a[j]=temp
class Vertex:
    def __init__(self,x,y):
        self.color = (255,255,255)
        self.x = x
        self.y = y

    def display(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),4,4)

    def getPosition(self):
        return [self.x,self.y]

    def __str__(self):
        return str(self.x+", "+self.y)

def createVertexes(numOfVertexes):
    for i in range(numOfVertexes):
        vertexArray.append(Vertex(random.randint(0,width),random.randint(0,height)))
createVertexes(8)
def createPopulation():
    for i in range(300):
        population.append(vertexArray[:])
        for j in range(100):
            shuffle(population[i])
createPopulation()
def drawLines(vertexArray,color):
    for i in range(vertexArray.__len__()-1):
        pygame.draw.line(screen,color,vertexArray[i].getPosition(),vertexArray[i+1].getPosition(),1)
def calculateDistance(vertexArray):
    dist = 0
    for i in range(vertexArray.__len__()-1):
        dist += np.linalg.norm(np.asarray(vertexArray[i+1].getPosition())-np.asarray(vertexArray[i].getPosition()))
    return dist
def displayVertexes(vertexArray):
    for i in range(vertexArray.__len__()):
        vertexArray[i].display()
def calculateFitness():
    global bestDistance
    global bestEver
    for i in range(population.__len__()-1):
        d = calculateDistance(population[i])
        if d<bestDistance:
            bestDistance = d
            bestEver = population[i][:]
        fitness.append(1/d)
def getProbability(fitness,population):
    first = 0
    sum = 0
    for i in range(fitness.__len__() - 1):
        sum += fitness[i]
    r = random.uniform(0, sum)
    for i in range(fitness.__len__() - 1):
        if r<=fitness[i] and r>=first:
            return population[i]
        first = fitness[i]
    return population[random.randint(0,2)]

def pickOne(population,fitness):
    return getProbability(fitness,population)


def mutate(order):
    indexA = random.randint(0,order.__len__()-1)
    indexB = random.randint(0,order.__len__()-1)
    swap(order,indexA,indexB)

def nextGeneration():
    global population
    newPopulation=[]
    for i in range(population.__len__()-1):
        order = pickOne(population,fitness)
        mutate(order)
        newPopulation.append(order)
    population = newPopulation
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(bgColor)
    displayVertexes(vertexArray)
    calculateFitness()
    print(fitness[2])
    nextGeneration()
    drawLines(bestEver,(255, 0, 0))
    pygame.display.flip()

0 个答案:

没有答案