TensorFlow 中的张量 n 模乘积
Tensor n-mode product in TensorFlow
张量 and a matrix as defined here (section 2.5) and here is denoted by and is of size 之间的张量n模积。
Tensorflow中有没有实现这个操作的函数?如果不是,如何用当前的 API 来实现?到目前为止,我对这方面的答案的搜索没有成功。
理想情况下,我会设想一个函数以 X 和 U 以及 n 作为参数并返回它们对应的 n 模式乘积。
对于固定数量的维度,您可以使用 tf.einsum
轻松实现。如果至少 n
是静态已知的(不是符号张量,无论如何在急切模式下这永远不会成为问题),您可以 fiddle 使用字符串来获得通用版本:
import tensorflow as tf
def n_mode_product(x, u, n):
n = int(n)
# We need one letter per dimension
# (maybe you could find a workaround for this limitation)
if n > 26:
raise ValueError('n is too large.')
ind = ''.join(chr(ord('a') + i) for i in range(n))
exp = f'{ind}K...,JK->{ind}J...'
return tf.einsum(exp, x, u)
# Test
x = tf.ones((2, 3, 4, 5))
u = tf.ones((6, 4))
n = 2 # n is zero-based here
out = n_mode_product(x, u, n)
print(out.shape)
# (2, 3, 6, 5)
您也可以通过将 X 的第 n 轴移动到末尾,然后执行(批处理)来获得相同的结果) 与 UT 的矩阵乘积,最后将新的最后一维返回到第 n 位置,但我认为写起来不会更简单也不会更快。
张量
Tensorflow中有没有实现这个操作的函数?如果不是,如何用当前的 API 来实现?到目前为止,我对这方面的答案的搜索没有成功。
理想情况下,我会设想一个函数以 X 和 U 以及 n 作为参数并返回它们对应的 n 模式乘积。
对于固定数量的维度,您可以使用 tf.einsum
轻松实现。如果至少 n
是静态已知的(不是符号张量,无论如何在急切模式下这永远不会成为问题),您可以 fiddle 使用字符串来获得通用版本:
import tensorflow as tf
def n_mode_product(x, u, n):
n = int(n)
# We need one letter per dimension
# (maybe you could find a workaround for this limitation)
if n > 26:
raise ValueError('n is too large.')
ind = ''.join(chr(ord('a') + i) for i in range(n))
exp = f'{ind}K...,JK->{ind}J...'
return tf.einsum(exp, x, u)
# Test
x = tf.ones((2, 3, 4, 5))
u = tf.ones((6, 4))
n = 2 # n is zero-based here
out = n_mode_product(x, u, n)
print(out.shape)
# (2, 3, 6, 5)
您也可以通过将 X 的第 n 轴移动到末尾,然后执行(批处理)来获得相同的结果) 与 UT 的矩阵乘积,最后将新的最后一维返回到第 n 位置,但我认为写起来不会更简单也不会更快。