Path: blob/master/ga/tsp_solver/__pycache__/tspga.cpython-35.pyc
2594 views
5O@Y� � @ sm d d l Z d d l Z d d l Z d d l j Z d d l m Z d d l
m Z Gd d � d e � Z
d S)� N)�
namedtuple)�combinationsc @ s� e Z d Z d Z d d � Z d d � Z d d � Z d d � Z d
d � Z d d
� Z d d � Z
d d � Z d d � Z d S)�TSPGAa
Travel Salesman Problem using Genetic Algorithm
Parameters
----------
generation : int
number of iteration to train the algorithm
population_size : int
number of tours in the population
retain_rate : float between 0 ~ 1
the fraction of the best tour (shortest total distance)
in the population to retain, which is then used in the
crossover and mutation staget to generate the children
for the next generation
mutate_rate : float between 0 ~ 1
the probability that each tour will mutate
Example
-------
%matplotlib inline
import pandas as pd
from tsp_solver import TSPGA
import matplotlib.pyplot as plt
# toy dataset
tsp_data = pd.read_table(
'TSP_berlin52.txt',
skiprows = 1, # the first row is simply the number of cities
header = None,
names = [ 'city', 'x', 'y' ],
sep = ' '
)
# specify the parameters and fit the data
tsp_ga = TSPGA(
generation = 5000,
population_size = 250,
retain_rate = 0.5,
mutate_rate = 0.25
)
tsp_ga.fit(tsp_data)
# distance convergence plot, and the best tour's distance
# and the corresponding city tour
tsp_ga.convergence_plot()
tsp_ga.best_tour
Reference
---------
http://www.theprojectspot.com/tutorial-post/applying-a-genetic-algorithm-to-the-travelling-salesman-problem/5
c C s; | | _ | | _ | | _ | | _ t | | � | _ d S)N)�
generation�retain_rate�mutate_rate�population_size�int�
retain_len)�selfr r r r � r �6/Users/r631854/machine-learning/ga/tsp_solver/tspga.py�__init__? s
zTSPGA.__init__c C s� | j d | _ | d d g j | _ d d � t | d � D� | _ | j � | _ t d d d g � | _ | j
d | d � } g | _ x<