Home > OS >  How to broadcast a list in Python?
How to broadcast a list in Python?

Time:10-21

I need to broadcast a list in Python to a larger value. I'm actually working on a backpropogation algorithm without the use of Numpy. I don't have access too it in my limited development environment.

From what I understand when you use Numpy.dot() operation on two arrays, numpy will broadcast one array if it is smaller than the other so they are equal size.

   dW = np.dot(dZ, A_prev.T) / m 

How does Numpy handle broadcasting an array when the two are not divisible? That is, when the modulus of the two arrays does not equal 0?

In my case, I have two lists; len(dZ) is equal too 512 and len(A_prev) is equal too 741. How should I approach broadcasting dZ so it's the same size as A_prev?

What I've tried so far is:

dZ = dZ * (len(dZ)   (len(A_prev) % len(dZ)))

However, dZ turns out to be a huge number, around 16,000. I'm not sure why.

CodePudding user response:

you can try these :

suppose that dz is a 3 length array:

dz = [4,2,8]

and A_prev is 11 item array :

A_prev  = [0]*11

than to broadcatst dz to the lenght of A_prev , do this:

dz = dz* (len(A_prev)//len(dz)) 
dz = dz   dz[:len(A_prev)-len(dz)] 

and now dz is an 11 item array:

[4, 2, 8, 4, 2, 8, 4, 2, 8, 4, 2]

CodePudding user response:

I think you should do this manually and create a new array which has the correct dimensions. The Python motto is explicit is better than implicit after all. https://www.python.org/dev/peps/pep-0020/ Numpy uses a C backend and has many tricks to optimize expressions and therefore you can ignore a lot of technicalities. Also reusing variable names for data with a different type is confusing and bad practice.

CodePudding user response:

maybe you like do this without numpy and do this with itertools.cycle like below:

>>> from itertools import cycle

>>> dz = [4,2,8]
>>> itr = cycle(dz)
>>> [next(itr) for _ in range(11)] 
[4, 2, 8, 4, 2, 8, 4, 2, 8, 4, 2]
  • Related