tensor dot operation in python

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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]]] 

回答1:

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]]) 


回答2:

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]]]) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!