Search code examples
pythonpython-3.xjupyter-notebookgenetic-algorithmgenetic-programming

How can I generate random matrix value chromosome in python which the sum of each chromosome equals to 1?


I want to generate random matrix chromosome with max value 1.0, min value 0, and the size is 10, Which every each rows equals to 1.

I have randomize chromosome using random.uniform in matrix with max value 1.0, min value 0, and the size is 10. How do I need to do if I want every each rows equals to 1? Thank you.

Input

import random
import numpy

def create_reference_solution(chromosome_length):
    reference = numpy.random.uniform(low=0, high=1.0, size=(10,chromosome_length))  # Create array chromosome
    return reference
print(create_reference_solution(4))  # print array

Output

[[0.49610843 0.73632368 0.38089333 0.38195847]
 [0.97371743 0.8245768  0.7576383  0.69000418]
 [0.57430261 0.02274222 0.36947273 0.69866079]
 [0.89639171 0.69387191 0.23348819 0.98811965]
 [0.14153835 0.10603574 0.25907029 0.349709  ]
 [0.04914772 0.54748797 0.18464009 0.99592558]
 [0.09897709 0.71638782 0.31578413 0.15487327]
 [0.19852756 0.5675573  0.09665754 0.27815583]
 [0.9085627  0.0907393  0.0585448  0.00976053]
 [0.05092392 0.46098409 0.12467901 0.48316205]]

Solution

  • You can make an array of random numbers between zero and one that is one less than your chromosome length. Sort the list, then find the differences between 0 and the first, first and second...last and 1.0. You can think of these as divisions of the unit. np.diff() is handy for this because you can prepend 0 and append 1 to get exactly what you want.

    For example:

    import numpy as np
    
    chromosome_length = 4
    reference = np.random.uniform(low=0, high=1.0, size=(10,chromosome_length - 1))  # Create array chromosome
    reference.sort(axis = 1)
    
    diffs = np.diff(reference, prepend=0, append=1, axis=1)
    print(diffs)
    np.sum(diffs, axis=1)
    

    diffs will be something like:

    [[0.33912643 0.06899929 0.39308693 0.19878736]
     [0.09431517 0.1920815  0.5591725  0.15443084]
     [0.13874118 0.05951455 0.45170353 0.35004074]
     [0.07826248 0.09976879 0.27325618 0.54871255]
     [0.01879091 0.28365535 0.5275187  0.17003504]
     [0.13071614 0.60090562 0.1776917  0.09068653]
     [0.03938235 0.59978608 0.00799955 0.35283202]
     [0.14483008 0.51857752 0.31868394 0.01790846]
     [0.42866068 0.12372462 0.07070687 0.37690784]
     [0.25118504 0.10828291 0.45142439 0.18910767]]
    

    The sums of the rows is:

    array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])