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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…