1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to generate multiple lists/vectors (same length) that are unique or partially...

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have created the following function that can generate a list of 0s and 1s (basically a bitstring) using randomization.

    import numpy as np

    def generate_genome(length: int, max_individuals: int = 0):
    bits = None
    if max_individuals > 0:
    num_individuals = np.random.randint(1, max_individuals + 1)
    print(f'Will have maximum of {num_individuals} individuals')
    print('Controlled randomization')
    bits = np.full(length, 0)
    bits_flipped_ids = np.random.choice(range(0, length), size=num_individuals, replace=False)
    print(f'Following indices will be flipped: {sorted(bits_flipped_ids)}')
    np.put(a=bits, ind=bits_flipped_ids, v=1)
    else:
    print('Standard randomization')
    bits = np.random.choice([0, 1], size=length)

    genome = Genome(bits=bits.tolist())
    print(f'Genome bits: {genome.bits}')
    return genome


    It supports two modes:

    • without max_individuals - creates a bit-list of a specific length
    • with max_individuals - creates a bit-list of a specific length but also ensures that the number of 1s is not exceeding max_individuals. The placement of the 1s is at random indices (restricted by the allowed length of the list of course)

    This is part of a genetic algorithm I am working on. This would produce samples similar to the ones below:


    • without max_individuals

      generate_genome(10, 0)

      [0 1 1 0 0 1 1 1 1 0]
      [1 0 1 1 1 1 0 1 1 1]
      [0 1 0 1 0 1 1 0 0 0]
      [1 1 0 0 0 1 1 0 1 1]
      [0 1 0 0 1 0 0 1 0 0]

    • with max_individuals

      generate_genome(10, 0)

      [0 0 0 0 0 0 0 0 0 1] with bits flipped at [9]
      [0 0 0 1 0 1 0 1 0 0] with bits flipped at [3 5 7]
      [0 1 0 0 0 1 0 1 0 0] with bits flipped at [1 5 7]
      [0 1 0 1 0 0 0 0 0 0] with bits flipped at [1 3]

    My problem is that there is the possibility of generating same bit-lists. This possibility increases with the smaller length and max_individuals are. I would like to have control over that to see how it affects my algorithm so I am looking for an efficient way to create a set of unique bit-lists using my function or even better - a set of bit-lists where the number of unique lists can be controlled by a parameter.

    Continue reading...

Compartilhe esta Página