NOTE: I am not looking for syntax on how to use np.subtract.outer, instead I am trying to solve a very specific issue that I am facing during its application.
I have a list of tuples -
a = [(0,0), (1,0), (1,1), (2,0), (2,2)]
a = np.array(a)
I am trying to implement a full vectorized subtraction between each element of this list (tuples). I can do it with iterating using itertools as shown below expecting a 5x5x2 as -
#My attempt with iteration (producing expected results)
np.array([np.array(i[0])-np.array(i[1]) for i in itertools.product(a, a)]).reshape(5,5,2)
#RESULT (5x5x2)
array([[[ 0, 0],
[-1, 0],
[-1, -1],
[-2, 0],
[-2, -2]],
[[ 1, 0],
[ 0, 0],
[ 0, -1],
[-1, 0],
[-1, -2]],
[[ 1, 1],
[ 0, 1],
[ 0, 0],
[-1, 1],
[-1, -1]],
[[ 2, 0],
[ 1, 0],
[ 1, -1],
[ 0, 0],
[ 0, -2]],
[[ 2, 2],
[ 1, 2],
[ 1, 1],
[ 0, 2],
[ 0, 0]]])
However, when using np.subtract.outer(). I end up with an array of shape 5x2x5x2 as below -
#My attempt with vectorization (producing unexpected results)
np.subtract.outer(a,a) #5x2x5x2
array([[[[ 0, 0], #This matrix is same as ....
[-1, 0],
[-1, -1],
[-2, 0],
[-2, -2]],
[[ 0, 0], #This one...
[-1, 0],
[-1, -1],
[-2, 0],
[-2, -2]]],
[[[ 1, 1], #However, this ...
[ 0, 1],
[ 0, 0],
[-1, 1],
[-1, -1]],
[[ 0, 0], #And this, dont repeat! ..
[-1, 0],
[-1, -1],
[-2, 0],
[-2, -2]]],
[[[ 1, 1], #This ...
[ 0, 1],
[ 0, 0],
[-1, 1],
[-1, -1]],
[[ 1, 1], #And this do..
[ 0, 1],
[ 0, 0],
[-1, 1],
[-1, -1]]],
[[[ 2, 2],
[ 1, 2],
[ 1, 1],
[ 0, 2],
[ 0, 0]],
[[ 0, 0],
[-1, 0],
[-1, -1],
[-2, 0],
[-2, -2]]],
[[[ 2, 2],
[ 1, 2],
[ 1, 1],
[ 0, 2],
[ 0, 0]],
[[ 2, 2],
[ 1, 2],
[ 1, 1],
[ 0, 2],
[ 0, 0]]]])
On inspection, I see that some of the matrices are actually repeating two times, while for others it's not the case (as commented above) in output.
My questions are -
- Why is this duplication happening?
- How to use
np.subtract.outercorrectly for this example? - (or,) How to transform the matrix to the expected one? (5x2x5x2) -> (5x5x2)
Note: this is only a toy example. The original list of tuples is massive and float32.