python - tensorflow einsum vs. matmul vs. tensordot

标签 python tensorflow numpy-einsum

在 tensorflow 中,函数 tf.einsumtf.matmultf.tensordot 都可以用于相同的任务。 (我意识到 tf.einsumtf.tensordot 有更通用的定义;我也意识到 tf.matmul 有批处理功能。)在在可以使用这三个中的任何一个的情况下,一个功能往往是最快的吗?还有其他推荐规则吗?

例如,假设 A 是 rank-2 张量,b 是 rank-1 张量,您想要计算乘积 c_j = A_ij b_j。三个选项中:

c = tf.einsum('ij,j->i', A, b)

c = tf.matmul(A, tf.expand_dims(b,1))

c = tf.tensordot(A, b, 1)

有没有比其他人更受欢迎的?

最佳答案

两者都是tf.tensordot()tf.einsum()是包装一个或多个调用 tf.matmul() 的语法糖(虽然在某些特殊情况下 tf.einsum() 可以减少到更简单的元素 tf.multiply() )。

在极限情况下,我希望所有三个函数对于相同的计算具有相同的性能。然而,对于较小的矩阵,直接使用 tf.matmul() 可能更有效,因为它会产生一个更简单的 TensorFlow 图,操作更少,因此预操作调用成本会更低.

关于python - tensorflow einsum vs. matmul vs. tensordot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100679/

相关文章:

python - for 循环等效于 einsum 表达式

python - torch.einsum 的内存使用

python - 如何在python中模拟const变量

python - 在 python 中画一条线直到掩码 OpenCV 的边缘

python - 如何从selenium page_source获取内容类型

python - Keras:如何使用来自另一个张量的信息对张量进行切片?

python - 检查向量的准确性

tensorflow - 训练神经网络 : Mathematical reason for Nan due to batch size

python - numpy:通过广播摆脱 for 循环

python - 防止 web2py 缓存?