com2014-template/Workshop - 6 (GA, SOM).ipynb

193 KiB

None <html> <head> </head>

Make sure you run this at the begining

In [1]:
import os
import sys
import math
import numpy as np
import matplotlib.pyplot as plt

# Append template path to sys path
sys.path.append(os.getcwd() + "/template")
In [2]:
from utils.load_data import load_data
from utils.load_data import log
from utils.visualize_tsp import plotTSP
from utils.tsp import TSP
from utils.tsp import TSP_Bench
from utils.tsp import TSP_Bench_ALL

Workshop Starts Here

TSP
solutions

Get familiar with your dataset

There are problems at different levels. 3 simple, 2 medium, 1 hard.

In [3]:
for root, _, files in os.walk('./template/data'):
    if(files):
        for f in files:
            print(str(root) + "/" + f)
./template/data/medium/pcb442.tsp
./template/data/medium/a280.tsp
./template/data/hard/dsj1000.tsp
./template/data/simple/att48.tsp
./template/data/simple/ulysses16.tsp
./template/data/simple/st70.tsp
In [4]:
ulysses16 = np.array(load_data("./template/data/simple/ulysses16.tsp"))
In [5]:
ulysses16[:]
Out[5]:
array([[38.24, 20.42],
       [39.57, 26.15],
       [40.56, 25.32],
       [36.26, 23.12],
       [33.48, 10.54],
       [37.56, 12.19],
       [38.42, 13.11],
       [37.52, 20.44],
       [41.23,  9.1 ],
       [41.17, 13.05],
       [36.08, -5.21],
       [38.47, 15.13],
       [38.15, 15.35],
       [37.51, 15.17],
       [35.49, 14.32],
       [39.36, 19.56]])
In [6]:
plt.scatter(ulysses16[:, 0], ulysses16[:, 1])
for i in range(0, 16):
    plt.annotate(i, (ulysses16[i, 0], ulysses16[i, 1]+0.5))

Naive Solution: In Order

In [7]:
simple_sequence = list(range(0, 16))
print(simple_sequence)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In [8]:
plotTSP([simple_sequence], ulysses16, num_iters=1)

Naive Solution: Random Permutation

In [9]:
random_permutation = np.random.permutation(16).tolist()
print(random_permutation)
[1, 8, 9, 12, 3, 2, 6, 11, 0, 14, 15, 7, 4, 5, 13, 10]
In [10]:
plotTSP([random_permutation], ulysses16, num_iters=1)

Best Solution

In [11]:
best_ulysses16 = [0, 13, 12, 11, 6, 5, 14, 4, 10, 8, 9, 15, 2, 1, 3, 7]
plotTSP([best_ulysses16], ulysses16, num_iters=1)

Calculate Fitness (Sum of all Distances)

In [12]:
def dist(node_0, node_1, coords):
        """
        Euclidean distance between two nodes.
        """
        coord_0, coord_1 = coords[node_0], coords[node_1]
        return math.sqrt((coord_0[0] - coord_1[0]) ** 2 + (coord_0[1] - coord_1[1]) ** 2)
In [13]:
print("Coordinate of City 0:", ulysses16[0])
Coordinate of City 0: [38.24 20.42]
In [14]:
print("Coordinate of City 1:", ulysses16[1])
Coordinate of City 1: [39.57 26.15]
In [15]:
print("Distance Between", dist(0, 1, ulysses16))
Distance Between 5.882329470541408
In [16]:
def fitness(solution, coords):
    N = len(coords)
    cur_fit = 0
    for i in range(len(solution)):
        cur_fit += dist(solution[i % N], solution[(i + 1) % N], coords)
    return cur_fit
In [17]:
print ("Order Fitness:\t", fitness(simple_sequence, ulysses16))
print ("Random Fitness:\t", fitness(random_permutation, ulysses16))
print ("Best Fitness:\t", fitness(best_ulysses16, ulysses16))
Order Fitness:	 104.42225210207233
Random Fitness:	 142.71833065004333
Best Fitness:	 74.10873595815309

Naive Random Model

In [18]:
import math
import random
from model.base_model import Model

class MyRandomModel(Model):
    def __init__(self):
        super().__init__()

    def init(self, nodes):
        """
        Put your initialization here.
        """
        super().init(nodes)

    def fit(self, max_it):
        """
        Put your iteration process here.
        """
        random_solutions = []
        for i in range(0, max_it):
            solution = np.random.permutation(self.N).tolist()
            random_solutions.append(solution)
            self.fitness_list.append(self.fitness(solution))

        self.best_solution = random_solutions[self.fitness_list.index(min(self.fitness_list))]
        return self.best_solution, self.fitness_list
In [19]:
tsp_file = './template/data/simple/ulysses16.tsp'
In [20]:
model = MyRandomModel()
best_solution, fitness_list, time = TSP_Bench(tsp_file, model, max_it=100)
[*] [Node] 16, [Best] 108.63032651658955
[*] Running for: 0.01 seconds

In [21]:
plt.plot(fitness_list, 'o-')
Out[21]:
[<matplotlib.lines.Line2D at 0x7f2942d60070>]

Genetic Algorithm

In [244]:
class Gene:  # City
    def __init__(self, name, lat, lng):
        self.name = name
        self.lat = lat
        self.lng = lng

    def get_distance_to(self, dest):
        return math.sqrt( (self.lng - dest.lng) ** 2 + (self.lat - dest.lat) ** 2 )

class Individual:  # Route: possible solution to TSP
    def __init__(self, genes):
        assert(len(genes) > 3)
        self.genes = genes
        self.__reset_params()

    def swap(self, gene_1, gene_2):
        self.genes[0]
        a, b = self.genes.index(gene_1), self.genes.index(gene_2)
        self.genes[b], self.genes[a] = self.genes[a], self.genes[b]
        self.__reset_params()

    def add(self, gene):
        self.genes.append(gene)
        self.__reset_params()

    @property
    def fitness(self):
        if self.__fitness == 0:
            self.__fitness = 1 / self.travel_cost  # Normalize travel cost
        return self.__fitness

    @property
    def travel_cost(self):  # Get total travelling cost
        if self.__travel_cost == 0:
            for i in range(len(self.genes)):
                origin = self.genes[i]
                if i == len(self.genes) - 1:
                    dest = self.genes[0]
                else:
                    dest = self.genes[i+1]

                self.__travel_cost += origin.get_distance_to(dest)

        return self.__travel_cost

    def __reset_params(self):
        self.__travel_cost = 0
        self.__fitness = 0

class Population:  # Population of individuals
    def __init__(self, individuals):
        self.individuals = individuals

    @staticmethod
    def gen_individuals(sz, genes):
        individuals = []
        for _ in range(sz):
            individuals.append(Individual(sample(genes, len(genes))))
        return Population(individuals)

    def add(self, route):
        self.individuals.append(route)

    def rmv(self, route):
        self.individuals.remove(route)

    def get_fittest(self):
        fittest = self.individuals[0]
        for route in self.individuals:
            if route.fitness > fittest.fitness:
                fittest = route

        return fittest
In [380]:
import math
import random
from model.base_model import Model
from random import randint, sample

class MyGAModel(Model):
    def __init__(self):
        super().__init__()
        self.iteration = 0

    def init(self, nodes):
        super().init(nodes)

    def evolve(self, pop, tourn_size, mut_rate):
        new_generation = Population([])
        pop_size = len(pop.individuals)
        elitism_num = pop_size // 4

        # Elitism
        for _ in range(elitism_num):
            fittest = pop.get_fittest()
            new_generation.add(fittest)
            pop.rmv(fittest)

        # Crossover
        for _ in range(elitism_num, pop_size):
            parent_1 = self.selection(new_generation, tourn_size)
            parent_2 = self.selection(new_generation, tourn_size)
            child = self.crossover(parent_1, parent_2)
            new_generation.add(child)

        # Mutation
        for i in range(elitism_num, pop_size):
            self.mutate(new_generation.individuals[i], mut_rate)

        return new_generation

    def crossover(self, parent_1, parent_2):
        def fill_with_parent1_genes(child, parent, genes_n):
            start_at = randint(0, len(parent.genes)-genes_n-1)
            finish_at = start_at + genes_n
            for i in range(start_at, finish_at):
                child.genes[i] = parent_1.genes[i]

        def fill_with_parent2_genes(child, parent):
            j = 0
            for i in range(0, len(parent.genes)):
                if child.genes[i] == None:
                    while parent.genes[j] in child.genes:
                        j += 1
                    child.genes[i] = parent.genes[j]
                    j += 1

        genes_n = len(parent_1.genes)
        child = Individual([None for _ in range(genes_n)])
        fill_with_parent1_genes(child, parent_1, genes_n // 2)
        fill_with_parent2_genes(child, parent_2)

        return child

    def mutate(self, individual, rate):
        for _ in range(len(individual.genes)):
            if random.random() < rate:
                sel_genes = sample(individual.genes, 2)
                individual.swap(sel_genes[0], sel_genes[1])

    def selection(self, population, competitors_n):
        return Population(sample(population.individuals, competitors_n)).get_fittest()

    def fit(self, max_it=20):
        """
        Execute simulated annealing algorithm.
        """
        pop_size = 1000
        mut_rate = 0.9
        tourn_size = 100

        genes = [Gene(num, city[0], city[1]) for num, city in enumerate(self.coords)]
        self.genes = genes

        population = Population.gen_individuals(pop_size, genes)
        

        for it in range(0, max_it):
            mut_rate = mut_rate * 0.95
            if mut_rate < 0.05:
                mut_rate = 0.05
            population = self.evolve(population, tourn_size, mut_rate)
            cost = population.get_fittest().travel_cost

            it += 1
            self.fitness_list.append(cost)
            print("[step] ", it, " [mut] ", mut_rate, " [best] ", self.fitness_list[self.fitness_list.index(min(self.fitness_list))])

        self.best_solution = [gene.name for gene in population.get_fittest().genes]

        return self.best_solution, self.fitness_list
In [381]:
tsp_problem = "./template/data/simple/ulysses16.tsp"
In [382]:
model = MyGAModel()

print("Genetic Algorithm")
best_solution, fitness_list, time = TSP_Bench(tsp_problem, model, max_it=200)
Genetic Algorithm
[step]  1  [mut]  0.855  [best]  96.11229392543888
[step]  2  [mut]  0.8122499999999999  [best]  93.76996122899693
[step]  3  [mut]  0.7716374999999999  [best]  93.76996122899693
[step]  4  [mut]  0.7330556249999999  [best]  93.36477102051143
[step]  5  [mut]  0.6964028437499998  [best]  93.36477102051143
[step]  6  [mut]  0.6615827015624998  [best]  93.36477102051143
[step]  7  [mut]  0.6285035664843748  [best]  90.01149831972343
[step]  8  [mut]  0.597078388160156  [best]  90.01149831972343
[step]  9  [mut]  0.5672244687521482  [best]  89.10668237027161
[step]  10  [mut]  0.5388632453145408  [best]  89.10668237027161
[step]  11  [mut]  0.5119200830488138  [best]  89.10668237027161
[step]  12  [mut]  0.486324078896373  [best]  75.20103046245312
[step]  13  [mut]  0.4620078749515544  [best]  75.20103046245312
[step]  14  [mut]  0.43890748120397666  [best]  75.20103046245312
[step]  15  [mut]  0.4169621071437778  [best]  75.10440611823527
[step]  16  [mut]  0.3961140017865889  [best]  75.10440611823527
[step]  17  [mut]  0.37630830169725943  [best]  74.94828839659989
[step]  18  [mut]  0.3574928866123964  [best]  74.94828839659989
[step]  19  [mut]  0.33961824228177656  [best]  74.94828839659989
[step]  20  [mut]  0.3226373301676877  [best]  74.94828839659989
[step]  21  [mut]  0.3065054636593033  [best]  74.94828839659989
[step]  22  [mut]  0.29118019047633814  [best]  74.23355449180846
[step]  23  [mut]  0.2766211809525212  [best]  74.21961177789215
[step]  24  [mut]  0.26279012190489515  [best]  74.21961177789215
[step]  25  [mut]  0.24965061580965037  [best]  74.21961177789215
[step]  26  [mut]  0.23716808501916783  [best]  73.987618045175
[step]  27  [mut]  0.22530968076820942  [best]  73.987618045175
[step]  28  [mut]  0.21404419672979894  [best]  73.987618045175
[step]  29  [mut]  0.20334198689330898  [best]  73.987618045175
[step]  30  [mut]  0.19317488754864354  [best]  73.987618045175
[step]  31  [mut]  0.18351614317121134  [best]  73.987618045175
[step]  32  [mut]  0.17434033601265078  [best]  73.987618045175
[step]  33  [mut]  0.16562331921201823  [best]  73.987618045175
[step]  34  [mut]  0.15734215325141732  [best]  73.987618045175
[step]  35  [mut]  0.14947504558884644  [best]  73.987618045175
[step]  36  [mut]  0.14200129330940411  [best]  73.987618045175
[step]  37  [mut]  0.1349012286439339  [best]  73.987618045175
[step]  38  [mut]  0.1281561672117372  [best]  73.987618045175
[step]  39  [mut]  0.12174835885115033  [best]  73.987618045175
[step]  40  [mut]  0.11566094090859282  [best]  73.987618045175
[step]  41  [mut]  0.10987789386316317  [best]  73.987618045175
[step]  42  [mut]  0.104383999170005  [best]  73.987618045175
[step]  43  [mut]  0.09916479921150474  [best]  73.987618045175
[step]  44  [mut]  0.0942065592509295  [best]  73.987618045175
[step]  45  [mut]  0.08949623128838302  [best]  73.987618045175
[step]  46  [mut]  0.08502141972396386  [best]  73.987618045175
[step]  47  [mut]  0.08077034873776566  [best]  73.987618045175
[step]  48  [mut]  0.07673183130087738  [best]  73.987618045175
[step]  49  [mut]  0.0728952397358335  [best]  73.987618045175
[step]  50  [mut]  0.06925047774904183  [best]  73.987618045175
[step]  51  [mut]  0.06578795386158974  [best]  73.987618045175
[step]  52  [mut]  0.06249855616851025  [best]  73.987618045175
[step]  53  [mut]  0.05937362836008474  [best]  73.987618045175
[step]  54  [mut]  0.0564049469420805  [best]  73.987618045175
[step]  55  [mut]  0.05358469959497647  [best]  73.987618045175
[step]  56  [mut]  0.050905464615227644  [best]  73.987618045175
[step]  57  [mut]  0.05  [best]  73.987618045175
[step]  58  [mut]  0.05  [best]  73.987618045175
[step]  59  [mut]  0.05  [best]  73.987618045175
[step]  60  [mut]  0.05  [best]  73.987618045175
[step]  61  [mut]  0.05  [best]  73.987618045175
[step]  62  [mut]  0.05  [best]  73.987618045175
[step]  63  [mut]  0.05  [best]  73.987618045175
[step]  64  [mut]  0.05  [best]  73.987618045175
[step]  65  [mut]  0.05  [best]  73.987618045175
[step]  66  [mut]  0.05  [best]  73.987618045175
[step]  67  [mut]  0.05  [best]  73.987618045175
[step]  68  [mut]  0.05  [best]  73.987618045175
[step]  69  [mut]  0.05  [best]  73.987618045175
[step]  70  [mut]  0.05  [best]  73.987618045175
[step]  71  [mut]  0.05  [best]  73.987618045175
[step]  72  [mut]  0.05  [best]  73.987618045175
[step]  73  [mut]  0.05  [best]  73.987618045175
[step]  74  [mut]  0.05  [best]  73.987618045175
[step]  75  [mut]  0.05  [best]  73.987618045175
[step]  76  [mut]  0.05  [best]  73.987618045175
[step]  77  [mut]  0.05  [best]  73.987618045175
[step]  78  [mut]  0.05  [best]  73.987618045175
[step]  79  [mut]  0.05  [best]  73.987618045175
[step]  80  [mut]  0.05  [best]  73.987618045175
[step]  81  [mut]  0.05  [best]  73.987618045175
[step]  82  [mut]  0.05  [best]  73.987618045175
[step]  83  [mut]  0.05  [best]  73.987618045175
[step]  84  [mut]  0.05  [best]  73.987618045175
[step]  85  [mut]  0.05  [best]  73.987618045175
[step]  86  [mut]  0.05  [best]  73.987618045175
[step]  87  [mut]  0.05  [best]  73.987618045175
[step]  88  [mut]  0.05  [best]  73.987618045175
[step]  89  [mut]  0.05  [best]  73.987618045175
[step]  90  [mut]  0.05  [best]  73.987618045175
[step]  91  [mut]  0.05  [best]  73.987618045175
[step]  92  [mut]  0.05  [best]  73.987618045175
[step]  93  [mut]  0.05  [best]  73.987618045175
[step]  94  [mut]  0.05  [best]  73.987618045175
[step]  95  [mut]  0.05  [best]  73.987618045175
[step]  96  [mut]  0.05  [best]  73.987618045175
[step]  97  [mut]  0.05  [best]  73.987618045175
[step]  98  [mut]  0.05  [best]  73.987618045175
[step]  99  [mut]  0.05  [best]  73.987618045175
[step]  100  [mut]  0.05  [best]  73.987618045175
[step]  101  [mut]  0.05  [best]  73.987618045175
[step]  102  [mut]  0.05  [best]  73.987618045175
[step]  103  [mut]  0.05  [best]  73.987618045175
[step]  104  [mut]  0.05  [best]  73.987618045175
[step]  105  [mut]  0.05  [best]  73.987618045175
[step]  106  [mut]  0.05  [best]  73.987618045175
[step]  107  [mut]  0.05  [best]  73.987618045175
[step]  108  [mut]  0.05  [best]  73.987618045175
[step]  109  [mut]  0.05  [best]  73.987618045175
[step]  110  [mut]  0.05  [best]  73.987618045175
[step]  111  [mut]  0.05  [best]  73.987618045175
[step]  112  [mut]  0.05  [best]  73.987618045175
[step]  113  [mut]  0.05  [best]  73.987618045175
[step]  114  [mut]  0.05  [best]  73.987618045175
[step]  115  [mut]  0.05  [best]  73.987618045175
[step]  116  [mut]  0.05  [best]  73.987618045175
[step]  117  [mut]  0.05  [best]  73.987618045175
[step]  118  [mut]  0.05  [best]  73.987618045175
[step]  119  [mut]  0.05  [best]  73.987618045175
[step]  120  [mut]  0.05  [best]  73.987618045175
[step]  121  [mut]  0.05  [best]  73.987618045175
[step]  122  [mut]  0.05  [best]  73.987618045175
[step]  123  [mut]  0.05  [best]  73.987618045175
[step]  124  [mut]  0.05  [best]  73.987618045175
[step]  125  [mut]  0.05  [best]  73.987618045175
[step]  126  [mut]  0.05  [best]  73.987618045175
[step]  127  [mut]  0.05  [best]  73.987618045175
[step]  128  [mut]  0.05  [best]  73.987618045175
[step]  129  [mut]  0.05  [best]  73.987618045175
[step]  130  [mut]  0.05  [best]  73.987618045175
[step]  131  [mut]  0.05  [best]  73.987618045175
[step]  132  [mut]  0.05  [best]  73.987618045175
[step]  133  [mut]  0.05  [best]  73.987618045175
[step]  134  [mut]  0.05  [best]  73.987618045175
[step]  135  [mut]  0.05  [best]  73.987618045175
[step]  136  [mut]  0.05  [best]  73.987618045175
[step]  137  [mut]  0.05  [best]  73.987618045175
[step]  138  [mut]  0.05  [best]  73.987618045175
[step]  139  [mut]  0.05  [best]  73.987618045175
[step]  140  [mut]  0.05  [best]  73.987618045175
[step]  141  [mut]  0.05  [best]  73.987618045175
[step]  142  [mut]  0.05  [best]  73.987618045175
[step]  143  [mut]  0.05  [best]  73.987618045175
[step]  144  [mut]  0.05  [best]  73.987618045175
[step]  145  [mut]  0.05  [best]  73.987618045175
[step]  146  [mut]  0.05  [best]  73.987618045175
[step]  147  [mut]  0.05  [best]  73.987618045175
[step]  148  [mut]  0.05  [best]  73.987618045175
[step]  149  [mut]  0.05  [best]  73.987618045175
[step]  150  [mut]  0.05  [best]  73.987618045175
[step]  151  [mut]  0.05  [best]  73.987618045175
[step]  152  [mut]  0.05  [best]  73.987618045175
[step]  153  [mut]  0.05  [best]  73.987618045175
[step]  154  [mut]  0.05  [best]  73.987618045175
[step]  155  [mut]  0.05  [best]  73.987618045175
[step]  156  [mut]  0.05  [best]  73.987618045175
[step]  157  [mut]  0.05  [best]  73.987618045175
[step]  158  [mut]  0.05  [best]  73.987618045175
[step]  159  [mut]  0.05  [best]  73.987618045175
[step]  160  [mut]  0.05  [best]  73.987618045175
[step]  161  [mut]  0.05  [best]  73.987618045175
[step]  162  [mut]  0.05  [best]  73.987618045175
[step]  163  [mut]  0.05  [best]  73.987618045175
[step]  164  [mut]  0.05  [best]  73.987618045175
[step]  165  [mut]  0.05  [best]  73.987618045175
[step]  166  [mut]  0.05  [best]  73.987618045175
[step]  167  [mut]  0.05  [best]  73.987618045175
[step]  168  [mut]  0.05  [best]  73.987618045175
[step]  169  [mut]  0.05  [best]  73.987618045175
[step]  170  [mut]  0.05  [best]  73.987618045175
[step]  171  [mut]  0.05  [best]  73.987618045175
[step]  172  [mut]  0.05  [best]  73.987618045175
[step]  173  [mut]  0.05  [best]  73.987618045175
[step]  174  [mut]  0.05  [best]  73.987618045175
[step]  175  [mut]  0.05  [best]  73.987618045175
[step]  176  [mut]  0.05  [best]  73.987618045175
[step]  177  [mut]  0.05  [best]  73.987618045175
[step]  178  [mut]  0.05  [best]  73.987618045175
[step]  179  [mut]  0.05  [best]  73.987618045175
[step]  180  [mut]  0.05  [best]  73.987618045175
[step]  181  [mut]  0.05  [best]  73.987618045175
[step]  182  [mut]  0.05  [best]  73.987618045175
[step]  183  [mut]  0.05  [best]  73.987618045175
[step]  184  [mut]  0.05  [best]  73.987618045175
[step]  185  [mut]  0.05  [best]  73.987618045175
[step]  186  [mut]  0.05  [best]  73.987618045175
[step]  187  [mut]  0.05  [best]  73.987618045175
[step]  188  [mut]  0.05  [best]  73.987618045175
[step]  189  [mut]  0.05  [best]  73.987618045175
[step]  190  [mut]  0.05  [best]  73.987618045175
[step]  191  [mut]  0.05  [best]  73.987618045175
[step]  192  [mut]  0.05  [best]  73.987618045175
[step]  193  [mut]  0.05  [best]  73.987618045175
[step]  194  [mut]  0.05  [best]  73.987618045175
[step]  195  [mut]  0.05  [best]  73.987618045175
[step]  196  [mut]  0.05  [best]  73.987618045175
[step]  197  [mut]  0.05  [best]  73.987618045175
[step]  198  [mut]  0.05  [best]  73.987618045175
[step]  199  [mut]  0.05  [best]  73.987618045175
[step]  200  [mut]  0.05  [best]  73.987618045175
[*] [Node] 16, [Best] 73.987618045175
[*] Running for: 32.92 seconds

In [383]:
plt.plot(fitness_list, 'o-')
Out[383]:
[<matplotlib.lines.Line2D at 0x7f2942624c70>]
In [384]:
plotTSP([best_solution], load_data(tsp_problem), num_iters=1)
In [386]:
print ("Best Fitness:\t", fitness(best_solution, ulysses16))
print ("Best Fitness:\t", fitness(best_ulysses16, ulysses16))
Best Fitness:	 73.987618045175
Best Fitness:	 74.10873595815309

Your Smart Model

In [72]:
import math
import random
from model.base_model import Model

class MyModel(Model):
    def __init__(self):
        super().__init__()

    def init(self, nodes):
        """
        Put your initialization here.
        """
        super().init(nodes)
        self.log("Nothing to initialize in your model now")

    def fit(self, max_it):
        """
        Put your iteration process here.
        """
        self.log("Naive Random Solution")
        self.best_solution = np.random.permutation(self.N).tolist()
        self.fitness_list.append(self.fitness(self.best_solution))

        return self.best_solution, self.fitness_list

Test your Model

In [73]:
tsp_problem = './template/data/simple/ulysses16.tsp'
In [74]:
model = MyModel()
best_solution, fitness_list, time = TSP_Bench(tsp_file, model)
[MyModel] Nothing to initialize in your model now
[MyModel] Naive Random Solution
[*] [Node] 16, [Best] 147.19356281214667
[*] Running for: 0.01 seconds

Test All Dataset

In [90]:
for root, _, files in os.walk('./template/data'):
    if(files):
        for f in files:
            print(str(root) + "/" + f)
./template/data/medium/pcb442.tsp
./template/data/medium/a280.tsp
./template/data/hard/dsj1000.tsp
./template/data/simple/att48.tsp
./template/data/simple/ulysses16.tsp
./template/data/simple/st70.tsp
In [91]:
def plot_results(best_solutions, times, title):
    fig = plt.figure()
    nodes = [len(s) for s in best_solutions]
    data = np.array([[node, time] for node, time in sorted(zip(nodes, times))])
    plt.plot(data[:, 0], data[:, 1], 'o-')
    fig.suptitle(title, fontsize=20)
In [94]:
tsp_path = './template/data/medium'
In [95]:
model = MyRandomModel()

print("Random Search")
best_solutions, fitness_lists, times = TSP_Bench_ALL(tsp_path, model)
Random Search
[*] ./template/data/medium/pcb442.tsp
[*] [Node] 442, [Best] 722875.708265324
[*] Running for: 0.26 seconds

[*] ./template/data/medium/a280.tsp
[*] [Node] 280, [Best] 31126.512432333657
[*] Running for: 0.16 seconds

In [79]:
plot_results(best_solutions, times, "Random Model")
In [82]:
model = MyGAModel()

print("Genetic Algorithm")
best_solutions, fitness_lists, times = TSP_Bench_ALL(tsp_path, model, max_it=100, timeout=600)
Genetic Algorithm
[*] ./template/data/medium/pcb442.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.12 seconds

[*] ./template/data/medium/a280.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.05 seconds

[*] ./template/data/hard/dsj1000.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.38 seconds

[*] ./template/data/simple/att48.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.01 seconds

[*] ./template/data/simple/ulysses16.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.00 seconds

[*] ./template/data/simple/st70.tsp
'module' object is not callable
[*] Unkown -4
[*] No Answer -1
[*] Running for: 0.01 seconds

In [81]:
plot_results(best_solutions, times, "Genetic Algorithm")
In [ ]:

In [ ]:

</html>