简体   繁体   English

np.einsum('mk,nk', D, D) 做什么?

[英]What does np.einsum('mk,nk', D, D) do?

I'm reading over someone else's code and am unsure what np.einsum does in this case.我正在阅读其他人的代码,但不确定 np.einsum 在这种情况下会做什么。

print(np.einsum('mk,nk', D, D)) # D is an np array with shape (3, 100)

This code outputs an array with shape (3, 3).此代码输出形状为 (3, 3) 的数组。

Any help is appreciated!任何帮助表示赞赏!

There are four steps to convert your equation to einsum notation.将方程转换为 einsum 符号有四个步骤。 Lets take this equation as an example C[i,k] = sum_j A[i,j] * B[j,k]让我们以这个方程为例C[i,k] = sum_j A[i,j] * B[j,k]

First we drop the variable names.首先我们删除变量名。 We get ik = sum_j ij * jk We drop the sum_j term as it is implicit.我们得到ik = sum_j ij * jk我们删除 sum_j 项,因为它是隐式的。 We get ik = ij * jk We replace * with,.我们得到ik = ij * jk我们将 * 替换为,。 We get ik = ij, jk The output is on the RHS and is separated with -> sign.我们得到ik = ij, jk output 在 RHS 上,用 -> 符号分隔。 We get ij, jk -> ik The einsum interpreter just runs these 4 steps in reverse.我们得到 ij, jk -> ik einsum 解释器只是反向运行这 4 个步骤。 All indices missing in the result are summed over.结果中缺少的所有索引都被求和。

Here are some more examples from the docsstrong text以下是来自 docsstrong 文本的更多示例

# Matrix multiplication
einsum('ij,jk->ik', m0, m1)  # output[i,k] = sum_j m0[i,j] * m1[j, k]

# Dot product
einsum('i,i->', u, v)  # output = sum_i u[i]*v[i]

# Outer product
einsum('i,j->ij', u, v)  # output[i,j] = u[i]*v[j]

# Transpose
einsum('ij->ji', m)  # output[j,i] = m[i,j]

# Trace
einsum('ii', m)  # output[j,i] = trace(m) = sum_i m[i, i]

# Batch matrix multiplication
einsum('aij,ajk->aik', s, t)  # out[a,i,k] = sum_j s[a,i,j] * t[a, j, k]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM