Josef Ondrej
Josef Ondrej

Reputation: 159

SparseTensor * Vector

How can the following be achieved in tensorflow, when A is a tf.SparseTensor and b is a tf.Variable?

A = np.arange(5**2).reshape((5,5))
b = np.array([1.0, 2.0, 0.0, 0.0, 1.0])
C = A * b 

If I try the same notation, I get InvalidArgumentError: Provided indices are out-of-bounds w.r.t. dense side with broadcasted shape.

Upvotes: 0

Views: 422

Answers (1)

akuiper
akuiper

Reputation: 214957

* works for SparseTensor as well, your problem seems to be with related to the SparseTensor itself, you might have provided the indices that are out of the range of the shape you give to it, consider this example:

A_t = tf.SparseTensor(indices=[[0,6],[4,4]], values=[3.2,5.1], dense_shape=(5,5))

Notice the column index 6 is larger than the shape specified which should have maximum 5 columns, and this gives the same error as you've shown:

b = np.array([1.0, 2.0, 0.0, 0.0, 1.0])

B_t = tf.Variable(b, dtype=tf.float32)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(A_t * B_t))

InvalidArgumentError (see above for traceback): Provided indices are out-of-bounds w.r.t. dense side with broadcasted shape


Here is a working example:

A_t = tf.SparseTensor(indices=[[0,3],[4,4]], values=[3.2,5.1], dense_shape=(5,5)) 

b = np.array([1.0, 2.0, 0.0, 0.0, 1.0])
B_t = tf.Variable(b, dtype=tf.float32)


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(A_t * B_t))
# SparseTensorValue(indices=array([[0, 3],
#        [4, 4]], dtype=int64), values=array([ 0.       ,  5.0999999], dtype=float32), dense_shape=array([5, 5], dtype=int64))

Upvotes: 1

Related Questions