0

I need to generate the initial population of a genetic algorithm. Consider the following vector:

[20, 2, 20, 1.5, 5, 20, 5, 0.5, -0.5, 5, 20, 5, 3, 14, 70, 30, 10, 5, 5, 20, 8, 20, 2.5]

I would do this:

new_population = numpy.random.uniform(low=0.1, high=50.0, size=pop_size)

The problem is, some of the chromosomes in the problem space have different steps and different maximum values. Element 0 should be 1-100 with a step of 1 (So int). Element 3 should be 0.1-10 with a step of 0.1 (Float). What is the easiest way to do this randomization?

3 Answers 3

1

Since it seems that the ranges for your chromosomes are hard-coded, I suggest you generate all the numbers with only one numpy.random.uniform() with the smallest range you need i.e 0.1-10 in your example and then you multiply this obtained number by the following ratio:

wanted_range/base_range

In your example you would multiply by 10. ( note that the ratios between the steps and ranges has to be the same for this method)

Sign up to request clarification or add additional context in comments.

2 Comments

this way you might encounter problems where ratio of step vs bounds will not match.
you're right, I was still finishing to edit my answer
1

You didnt give enough data to see any pattern for shorter code.

However you could do the following: Make a list of lists where each sublist in composed of the following elements: bounds = [[low, high, step], ...]

Then initialize an empty numpy array, i.e. new_population = np.empty(23) And after that you can just loop through bounds with for loop and generate each element:

for i, value in enumerate(bounds):
    new_population[i] = np.random.uniform((low=value[0], high=value[1], size=value[2])

Comments

0

The numpy.vectorize decorator allows you to easily define functions which act over arrays of values, one element at a time. You can define your specific case as

@np.vectorize
def vectorized_random(low, high, step):
    # whatever kind of random value you want

which can be directly used over arrays of inputs.

>>> vectorized_random([1, 1, 0.1], [100, 10, 10], [1, 1, 0.1])
array([...])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.