4

I'm trying to make my code more efficient. I'm not super familiar with vectorization. I can do simple ones but I'm having trouble wrapping my head around this one

def mate(self, parent1, parent2):
    length = parent1.size
    parent1 *= 1e6
    parent2 *= 1e6
    parent1 = parent1.astype(int)
    parent2 = parent2.astype(int)
    child1 = []
    child2 = []
    for i in range(length):
        hold1 = parent1[i]
        hold2 = parent2[i]
        hold1 = np.binary_repr(hold1, 30)
        hold2 = np.binary_repr(hold2, 30)
        pivot = np.random.randint(0, length)
        childGene1 = hold1[:pivot] + hold2[pivot:]
        childGene2 = hold2[:pivot] + hold1[pivot:]
        childGene1 = int(childGene1, 2) / 1e6
        childGene2 = int(childGene2, 2) / 1e6
        child1.append(childGene1)
        child2.append(childGene2)            
    return [child1, child2]

It's a mating function I made for a genetic algorithm. How should I go about vectorizing this loop?

bobrobbob
  • 1,251
  • 11
  • 21
Piggle
  • 41
  • 2
  • By "map" do you mean a [list comprehension](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python)? – meowgoesthedog Jun 24 '18 at 22:13
  • 1
    In Python, `map` is used as `result = list(map(afun, alist))`, where `def fun(x):` returns a value. But why would you want to convert this loop to that? The fact that you are returning 2 lists complicates such a conversion. A `map` with 2 inputs: `list(map(lambda a,b: a+b, range(3),range(10,13)))` – hpaulj Jun 24 '18 at 22:14
  • I guess so? Maybe I'm more nave than I think. I'm just trying to remove for loops where ever I can. – Piggle Jun 24 '18 at 22:22
  • 2
    changing a forloop to a map wont make it more efficient (although it will set it up better for multiprocessing or something) – Joran Beasley Jun 24 '18 at 22:34
  • because of the gene-swapping i don't think you'll gain much by vectorizing your loop – bobrobbob Jun 24 '18 at 23:44
  • You could look into Cython or Numba to compile it to a more low level machine language, but for a single for loop like this it may be hard to optimize it much further than what you already have. – pythonweb Jun 25 '18 at 02:21
  • Originally this question asked about making a `map`, hence our puzzled comments. Now it asks about `vectorize`, a more common `numpy` question. – hpaulj Jun 25 '18 at 02:21
  • Help with `vectorizing` requires a [mvce], i.e. sample inputs for the function. – hpaulj Jun 25 '18 at 02:25
  • 1
    `binary_repr` only works an integer, so can't be applied the whole `parent1` array. Doing a different `pivot` for each `i` will also be hard to vectorize. – hpaulj Jun 25 '18 at 02:31
  • 1
    Possibly related: https://stackoverflow.com/questions/49175337/how-to-convert-array-of-integers-to-binary-encoding-in-tensorflow-or-numpy – hpaulj Jun 25 '18 at 04:34

0 Answers0