freude
freude

Reputation: 3832

tensor dot operation in python

I have two arrays A=[1,2,3] and B=[[1],[0],[1],[0]]. The question how to perform their tensor dot product in python. I am expecting to get:

C=[[1,2,3],
   [0,0,0],
   [1,2,3],
   [0,0,0]]

The function np.tensordot() returns an error concerning shapes of arrays.

A little addition to this question. How to do such operation if matrix are totally different in shape, like:

A=[[1,1,1,1],
   [1,1,1,1],
   [2,2,2,2],
   [3,3,3,3]]

B=[2,1]

C=[[[2,1],[2,1],[2,1],[2,1]],
   [[2,1],[2,1],[2,1],[2,1]],
   [[4,2],[4,2],[4,2],[4,2]],
   [[6,3],[6,3],[6,3],[6,3]]]

Upvotes: 2

Views: 3792

Answers (2)

EmanuelOverflow
EmanuelOverflow

Reputation: 348

I'm not so expert with this argument but if you try to change axes in numpy it works:

A=[1,2,3]
B=[[1],[0],[1],[0]]
np.tensordot(B, A, axes=0)
array([[[1, 2, 3]],

   [[0, 0, 0]],

   [[1, 2, 3]],

   [[0, 0, 0]]])

Upvotes: 3

Alfe
Alfe

Reputation: 59416

Try using correct numpy arrays:

>>> array([[1],[2],[3]]).dot(array([[1,0,1,0]]))
array([[1, 0, 1, 0],
       [2, 0, 2, 0],
       [3, 0, 3, 0]])

If your alignment is different, using a.transpose() can flip it:

>>> array([[1],[2],[3]]).dot(array([[1,0,1,0]])).transpose()
array([[1, 2, 3],
       [0, 0, 0],
       [1, 2, 3],
       [0, 0, 0]])

If you (for whatever reason) have to use tensordot(), try this:

>>> numpy.tensordot([1,2,3], [1,0,1,0], axes=0)
array([[1, 0, 1, 0],
       [2, 0, 2, 0],
       [3, 0, 3, 0]])

Upvotes: 6

Related Questions