sacgajcvs

Untitled

Nov 1st, 2019
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.97 KB | None | 0 0
  1. import numpy as np
  2. """
  3. f(x) = x*x + y*y - 5
  4. """
  5. # Initializing n = 6
  6. n = 6
  7. chromosome = np.random.randint(0,5,(n,2))
  8. # for num in chromosome:
  9. #   for vl in num:
  10. #     vl*=1.0
  11. print("chromosomes :",chromosome)
  12. epoch = 0
  13.  
  14. prev = 0;
  15.  
  16. while epoch <  200 :
  17.     objective = abs(5 - chromosome[:,0]**2 - chromosome[:,1]**2 )
  18.     avg = objective.sum()/n
  19.    
  20.     if abs(avg-prev)<1e-7 :
  21.       break
  22.     prev=avg
  23.    
  24.     print("Fitness object :", objective)
  25.     print("Avg: ",avg)
  26.  
  27.     # Selection of fittest chromosome
  28.     fitness =  1/(1 + objective)
  29.     print("Fitness :",fitness)
  30.    
  31.     # Calculating the total of fitness function
  32.     total = fitness.sum()
  33.     print("Total :",total)
  34.    
  35.    
  36.  
  37.     # Calculating Probablility for each chromosome
  38.     prob = fitness/total
  39.     print("Probability :",prob)
  40.    
  41.     # Selection using Roulette Wheel And Calculating Cumulative Probability
  42.     cum_sum = np.cumsum(prob)
  43.     print("Cumulative Sum :", cum_sum)
  44.    
  45.     # Generating Random Numbers in the range 0-1
  46.     Ran_nums = np.random.random((chromosome.shape[0]))
  47.     print("Random Numbers :",Ran_nums)
  48.    
  49.     # Making a new matrix of chromosome for calculation purpose
  50.     chromosome_2 = np.zeros((chromosome.shape[0],2))
  51.    
  52.     for i in range(Ran_nums.shape[0]):
  53.         for j in range(chromosome.shape[0]):
  54.             if Ran_nums[i]  < cum_sum[j]:
  55.                 chromosome_2[i,:] = chromosome[j,:]
  56.                 break
  57.            
  58.     chromosome = chromosome_2
  59.     print("Chromosomes after updation :",chromosome)
  60.        
  61.     # crossover
  62.     R = [np.random.random() for i in range(n)]
  63.     print("Random Values :",R)
  64.    
  65.     # Crossover Rate
  66.     pc = 0.25
  67.     flag = Ran_nums < pc
  68.     print("Flagged Values :",flag)
  69.    
  70.     # Determining the cross chromosomes
  71.     cross_chromosome = chromosome[[(i == True) for i in flag]]
  72.     print("Cross chromosome :",cross_chromosome)
  73.     len_cross_chrom = len(cross_chromosome)
  74.    
  75.     # Calculating cross values
  76.     # cross_values = np.random.randint(1,3,len_cross_chrom)
  77.     # print("Cross Values :",cross_values)
  78.    
  79.     cpy_chromosome = np.zeros(cross_chromosome.shape)
  80.    
  81.     # Performing Cross-Over
  82.    
  83.     # Copying the chromosome values for calculations
  84.     for i in range(cross_chromosome.shape[0]):
  85.         cpy_chromosome[i , :] = cross_chromosome[i , :]
  86.        
  87.     if len_cross_chrom == 1:
  88.         cross_chromosome = cross_chromosome
  89.     else :
  90.         for i in range(len_cross_chrom):
  91.             c_val = 1
  92.             if i == len_cross_chrom - 1 :
  93.                 cross_chromosome[i , c_val:] = cpy_chromosome[0 , c_val:]
  94.             else :
  95.                 cross_chromosome[i , c_val:] = cpy_chromosome[i+1 , c_val:]
  96.        
  97.     print("Crossovered Chromosome :",cross_chromosome)
  98.    
  99.     index_chromosome = 0
  100.     index_newchromosome = 0
  101.     for i in flag :
  102.         if i == True :
  103.             chromosome[index_chromosome, :] = cross_chromosome[index_newchromosome, :]
  104.             index_newchromosome = index_newchromosome + 1
  105.         index_chromosome = index_chromosome + 1
  106.    
  107.     print("New Chromosomes:", chromosome)
  108.    
  109.     # Calculating the total no. of generations
  110.     a ,b = chromosome.shape[0] ,chromosome.shape[1]
  111.     total_gen = a*b
  112.     print("Total Generations :",total_gen)
  113.    
  114.     #mutation rate = pm
  115.     pm = 0.1
  116.     no_of_mutations = int(np.round(pm * total_gen))
  117.     print("No. of Mutations :" ,no_of_mutations)
  118.    
  119.     # Calculating the Generation number
  120.     gen_num = np.random.randint(0,total_gen - 1, no_of_mutations)
  121.     print(" Generated Random Numbers : " , gen_num)
  122.    
  123.     # Generating a random number which can replace the selected chromosome to be mutated
  124.     Replacing_num = np.random.randint(0,5, no_of_mutations)
  125.     # for num in Replacing_num:
  126.     #   num*=1.0
  127.    
  128.     print(" Numbers to be replaced : " , Replacing_num)
  129.    
  130.     for i in range(no_of_mutations):
  131.         a = gen_num[i]
  132.         row = a//2
  133.         col = a%2
  134.         chromosome[row , col] = Replacing_num[i]
  135.    
  136.     print(" Chromosomes After Mutation : " , chromosome)
  137.  
  138.     epoch = epoch + 1
Advertisement
Add Comment
Please, Sign In to add comment