3D 稀疏张量与 2D 张量的矩阵乘法:InvalidArgumentError:张量“a_shape”必须具有 2 个元素 [Op:SparseTensorDenseMatMul]

3

嗨,我正在尝试使用2D张量进行3D SparseTensor矩阵乘法。这是一个玩具示例:

使用2D张量进行3D张量矩阵乘法

import tensorflow as tf
import numpy as np

a = np.array([[[1., 0., 2., 0.],
              [3., 0., 0., 4.]]])
b = (np.array([1., 2.])[:,np.newaxis]).T

a_t = tf.constant(a)
b_t = tf.constant(b)
    
tf.matmul(b_t,a_t)

<tf.Tensor: shape=(1, 1, 4), dtype=float64, numpy=array([[[7., 0., 2., 8.]]])>

使用2D张量进行3D SparseTensor矩阵乘法

import tensorflow as tf
import numpy as np

a = np.array([[[1., 0., 2., 0.],
              [3., 0., 0., 4.]]])
b = (np.array([1., 2.])[:,np.newaxis]).T

a_t = tf.constant(a)
b_t = tf.constant(b)

a_s = tf.sparse.from_dense(a_t)

tf.sparse.sparse_dense_matmul(b_t,a_s)

InvalidArgumentError: Tensor 'a_shape' must have 2 elements [Op:SparseTensorDenseMatMul]

你能帮我解决这个错误吗?

1个回答

0

文档中指出,密集矩阵的秩必须为2。

将稀疏张量(或秩为2的密集矩阵)“A”乘以密集矩阵

此函数调用的第一个参数是:

秩为2的稀疏张量(或密集矩阵)A。

因此,您至少不能用这种方式实现您想要的功能。似乎您并不真正需要三个维度,因为其中一个维度只有一个。如果您将其压缩掉,它就可以工作:

a_t = tf.constant(tf.squeeze(a))
b_t = tf.constant(b)

a_s = tf.sparse.from_dense(a_t)

tf.sparse.sparse_dense_matmul(b_t,a_s)

<tf.Tensor: shape=(1, 4), dtype=float64, numpy=array([[7., 0., 2., 8.]])>

1
感谢您查看这个问题。但不幸的是,我不能采用这种方法,因为我有多个第三维度。这意味着tf.sparse.sparse_dense_matmul无法处理三维张量? - S.Perera
那似乎是这种情况。我看到的唯一方法是在第三维/第三轴上使用for循环。虽然这不是矢量化方法,但效率低下。 - Arka Mukherjee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接