Tensorflow Dense_to_sparse [英] Tensorflow dense_to_sparse

查看:49
本文介绍了Tensorflow Dense_to_sparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将未压缩的稀疏数组转换为 tf.SparseTensor 接受的格式.有一个内置函数 tf.sparse_to_dense 与我想要做的完全相反.所以我的问题是 Tensorflow 或 Python 中是否有任何内置函数来进行这种转换?

I am trying to convert a uncompressed sparse array into a format accepted by tf.SparseTensor. There is an inbuilt function tf.sparse_to_dense that does exactly the opposite I am trying to do. So my question is there any inbuilt function in Tensorflow or Python to do this conversion?

推荐答案

根据对于这个问题:

你可以这样做:

您可以使用 tf.where 和 tf.gather_nd 来做到这一点:

You can use tf.where and tf.gather_nd to do that:

a = np.reshape(np.arange(24), (3, 4, 2))
with tf.Session() as sess:
    a_t = tf.constant(a)
    idx = tf.where(tf.not_equal(a_t, 0))
    # Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape() if tensor shape is dynamic
    sparse = tf.SparseTensor(idx, tf.gather_nd(a_t, idx), a_t.get_shape())
    dense = tf.sparse_tensor_to_dense(sparse)
    b = sess.run(dense)
np.all(a == b)
>>> True

这篇关于Tensorflow Dense_to_sparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆