Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ethen8181
GitHub Repository: ethen8181/machine-learning
Path: blob/master/ga/__pycache__/ga.cpython-35.pyc
2580 views


5O@Y��@s?ddlZddlZddlmZGdd�d�ZdS)�N)�
namedtuplec@s^eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�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
	cCse||_||_||_||_||_t||�|_||_tdddg�|_	dS)N�info�cost�chromo)
�low�high�pop_size�chromo_size�
generation�int�
retain_len�mutate_raterr)�selfrr	r
rrZretain_rater�r�(/Users/r631854/machine-learning/ga/ga.py�__init__s						zGA.__init__cCs�|j|jf}tjj|j|jd|�}|j||�}g|_x?t	|j
�D].}|j||�\}}|jj|�q_W|j|j
d|_
d|_|S)z1
		target : int
        	the targeted solution
		�T)r	r
�np�random�randintrr�
_compute_costZgeneration_history�ranger�_evolve�append�bestZ	is_fitted)r�target�
array_size�pop�
graded_pop�_�generation_bestrrr�fit+s"		zGA.fitcsTtjtj|dd�|�}�fdd�t||�D�}t|�}|S)zV
		combine the cost and chromosome into one list and sort them
		in ascending order
		�axisrcs.g|]$\}}�j|t|���qSr)r�list)�.0�p�c)rrr�
<listcomp>Hs	z$GA._compute_cost.<locals>.<listcomp>)r�abs�sum�zip�sorted)rrrr�gradedr)rrrBs""zGA._compute_costcCs�|d|j�}dd�|D�}g}xDt|�|jkrr|j|�}|j|�}|j|�q/W|j||�}|j|�t|�}|d|j�}|d}||fS)zt
		core method that does the crossover, mutation to generate
		the possibly best children for the next generation
		NcSsg|]}|j�qSr)r)r%r&rrrr(Us	zGA._evolve.<locals>.<listcomp>r)	r
�lenr	�
_crossover�_mutaterr�extendr,)rrr�parent�children�childZgraded_childrenr!rrrrMs

z
GA._evolvecCsktjt|j�dd�\}}||||}}t|�d}|d|�||d�}|S)z�
		mate the children by randomly choosing two parents and mix 
		the first half element of one parent with the later half 
		element of the other
		�k�N)r�samplerr
r.)rr2Zindex1�index2ZmaleZfemale�pivotr4rrrr/ks
$z
GA._crossovercCsG|jtj�krCtj|j�}tj|j|j�||<|S)zn
		randomly change one element of the chromosome if it
		exceeds the user-specified threshold (mutate_rate)
		)rr�	randranger
rrr)rr4Z
idx_to_mutaterrrr0xsz
GA._mutateN)
�__name__�
__module__�__qualname__�__doc__rr"rrr/r0rrrrrs
r)r�numpyr�collectionsrrrrrr�<module>s