python - python中的张量点运算

标签 python matrix numpy

我有两个数组 A=[1,2,3]B=[[1],[0],[1],[0]] .如何在 python 中执行张量点积的问题。我期望得到:

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

函数 np.tensordot() 返回有关数组形状的错误。

这个问题的一点补充。如果矩阵的形状完全不同,如何进行这样的操作,例如:

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

最佳答案

尝试使用正确的 numpy 数组:

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

如果您的对齐方式不同,使用 a.transpose() 可以翻转它:

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

如果您(无论出于何种原因)必须使用 tensordot(),请尝试以下操作:

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

关于python - python中的张量点运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296028/

相关文章:

algorithm - 从大型文本文件快速形成矩阵

python - 在 Cython 和 NumPy 中包装 C 函数

python - Jython 的 Numpy 模拟

python if语句里面有语法错误

python - 对数组进行冒泡排序所需的最小交换次数是多少?

Python - 将稀疏文件读入稀疏矩阵的最佳方法

python - 如何计算每个 scikit-learn ML 模型样本的二进制对数损失

python - 无法解决 ValueError : The create_choropleth figure factory requires the plotly-geo package

python - Django 默认使用 HTTPS

MATLAB 用零展开矩阵