I have the following code:
a = tf.constant([[10],
[0],
[4]])
s = tf.sparse.from_dense(a)
b = tf.constant([[3, 4],
[1, 2],
[2, 5]])
# print(tf.multiply(s, b)) # this didn't work either though it works if s is dense
print(s.__mul__(b))
I want to multiply a with each column of b getting:
[[30, 40],
[ 0, 0],
[ 8, 20]]
But the above code gives me an error that the sparse tensor cant be broadcasted to make the shapes match.
tensorflow.python.framework.errors_impl.InvalidArgumentError: SparseDenseBinaryOpShared broadcasts dense to sparse only; got incompatible shapes: [3,1] vs. [3,2] [Op:SparseDenseCwiseMul]
How do I achieve the above efficiently without materializing the sparse tensor a into a dense one?
CodePudding user response:
Not sure how efficient this is and if it is a viable option for you, but you could try using tf.TensorArray
with tf.sparse.sparse_dense_matmul
:
import tensorflow as tf
a = tf.constant([[10],
[0],
[4]])
s = tf.sparse.from_dense(a)
b = tf.constant([[3, 4],
[1, 2],
[2, 5]])
ta = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True)
for i in range(len(b)):
if i == len(b):
ta = ta.write(ta.size(), tf.sparse.sparse_dense_matmul(s, b[i:])[i])
else:
ta = ta.write(ta.size(), tf.sparse.sparse_dense_matmul(s, b[i:i 1])[i])
print(ta.stack())
tf.Tensor(
[[30 40]
[ 0 0]
[ 8 20]], shape=(3, 2), dtype=int32)