TensorFlow SparseTensor with dynamically set dense_shape

前端 未结 1 2000
天涯浪人
天涯浪人 2021-01-20 06:46

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 th

相关标签:
1条回答
  • 2021-01-20 07:37

    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.

    0 讨论(0)
提交回复
热议问题