Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65645776/exponential-of-sparsetensor-with-mapping

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...