Skip to content Skip to sidebar Skip to footer

Tensorflow Sparsetensor With Dynamically Set Dense_shape

I have previously asked this question Create boolean mask on TensorFlow about how to get a tensor only with certain indices set to 1, and the rest of them to 0. I thought the answe

Solution 1:

Here is what you can do to have a dynamic shape:

import tensorflow as tf 
import numpy as np

indices = tf.constant([[0, 0],[1, 1]], dtype=tf.int64)
values = tf.constant([1, 1])
dynamic_input = tf.placeholder(tf.float32, shape=[None, None])
s = tf.shape(dynamic_input, out_type=tf.int64)

st = tf.SparseTensor(indices, values, s)
st_ordered = tf.sparse_reorder(st)
result = tf.sparse_tensor_to_dense(st_ordered)

sess = tf.Session()

An input with (dynamic) shape [5, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([5, 3])})

Will output:

array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]], dtype=int32)

An input with (dynamic) shape [3, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([3, 3])})

Will output:

array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 0]], dtype=int32)

So there you go... dynamic sparse shape.

Post a Comment for "Tensorflow Sparsetensor With Dynamically Set Dense_shape"