Skip to content
Advertisement

Exponential of SparseTensor with mapping

I want to take the exp of each element in the sparse matrix. Here is a simple example:

a = np.array([[1, 0, 2, 0], [3, 0, 0, 4]])
a_t = tf.constant(a)
a_s = tf.sparse.from_dense(a_t)
tf.exp(a_s) 

But this gives the followig error:

ValueError: Attempt to convert a value (<tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x149fd57f0>) with an unsupported type (<class 'tensorflow.python.framework.sparse_tensor.SparseTensor'>) to a Tensor.

Can you please help me to sort this out without converting this to dense matrix?

Advertisement

Answer

If you have Tensorflow 2.4, you can use tf.sparse.map_values:

import tensorflow as tf
import numpy as np

a = np.array([[1., 0., 2., 0.],
              [3., 0., 0., 4.]])

a_t = tf.constant(a)
a_s = tf.sparse.from_dense(a_t)

Here is the magic:

tf.sparse.to_dense(tf.sparse.map_values(tf.exp, a_s))
<tf.Tensor: shape=(2, 4), dtype=float64, numpy=
array([[ 2.71828183,  0.        ,  7.3890561 ,  0.        ],
       [20.08553692,  0.        ,  0.        , 54.59815003]])>

Note that tf.sparse.to_dense is only there so we can visualize the result. Also, I had to convert your values to floating point.

Advertisement