I want to take the exp of each element in the sparse matrix. Here is a simple example:
JavaScript
x
5
1
a = np.array([[1, 0, 2, 0], [3, 0, 0, 4]])
2
a_t = tf.constant(a)
3
a_s = tf.sparse.from_dense(a_t)
4
tf.exp(a_s)
5
But this gives the followig error:
JavaScript
1
2
1
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.
2
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
:
JavaScript
1
9
1
import tensorflow as tf
2
import numpy as np
3
4
a = np.array([[1., 0., 2., 0.],
5
[3., 0., 0., 4.]])
6
7
a_t = tf.constant(a)
8
a_s = tf.sparse.from_dense(a_t)
9
Here is the magic:
JavaScript
1
2
1
tf.sparse.to_dense(tf.sparse.map_values(tf.exp, a_s))
2
JavaScript
1
4
1
<tf.Tensor: shape=(2, 4), dtype=float64, numpy=
2
array([[ 2.71828183, 0. , 7.3890561 , 0. ],
3
[20.08553692, 0. , 0. , 54.59815003]])>
4
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.