Path: blob/master/ga/__pycache__/ga.cpython-35.pyc
2580 views
5O@Y� � @ s? d d l Z d d l Z d d l m Z Gd d � d � Z d S)� N)�
namedtuplec @ 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 S)�GAaE
Genetic Algorithm for a simple optimization problem
Parameters
----------
generation : int
number of iteration to train the algorithm
pop_size : int
number of chromosomes in the population
chromo_size : int
number of possible values (genes) per chromosome
low, high : int
lower_bound and upper_bound possible value of the randomly generated chromosome
retain_rate : float 0 ~ 1
the fraction of the best chromosome to retain. used to mate
the children for the next generation
mutate_rate : float 0 ~ 1
the probability that each chromosome will mutate
c C se | | _ | | _ | | _ | | _ | | _ t | | � | _ | | _ t d d d g � | _ d S)N�info�cost�chromo)
�low�high�pop_size�chromo_size�
generation�int�
retain_len�mutate_rater r )�selfr r r
r r Zretain_rater � r �(/Users/r631854/machine-learning/ga/ga.py�__init__ s zGA.__init__c C s� | j | j f } t j j | j | j d | � } | j | | � } g | _ x? t | j
� D]. } | j | | � \ } } | j j | � q_ W| j | j
d | _
d | _ | S)z1
target : int
the targeted solution
� T)r r
�np�random�randintr r �
_compute_costZgeneration_history�ranger �_evolve�append�bestZ is_fitted)r �target�
array_size�pop�
graded_pop�_�generation_bestr r r �fit+ s " zGA.fitc sT t j t j | d d �| � } � f d d � t | | � D� } t | � } | S)zV
combine the cost and chromosome into one list and sort them
in ascending order
�axisr c s. g | ]$ \ } } � j | t | � � � q Sr )r �list)�.0�p�c)r r r �
<listcomp>H s z$GA._compute_cost.<locals>.<listcomp>)r �abs�sum�zip�sorted)r r r r �gradedr )r r r B s ""zGA._compute_costc C s� | d | j � } d d � | D� } g } xD t | � | j k rr | j | � } | j | � } | j | � q/ W| j | | � } | j | � t | � } | d | j � } | d } | | f S)zt
core method that does the crossover, mutation to generate
the possibly best children for the next generation
Nc S s g | ] } | j � q Sr )r )r% r&