来自密集张量 Tensorflow 的稀疏张量(矩阵) [英] Sparse Tensor (matrix) from a dense Tensor Tensorflow

查看:61
本文介绍了来自密集张量 Tensorflow 的稀疏张量(矩阵)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个卷积稀疏自动编码器,我需要将一个充满值的 4D 矩阵(其形状为 [samples, N, N, D])转换为一个稀疏矩阵.

I am creating a convolutional sparse autoencoder and I need to convert a 4D matrix full of values (whose shape is [samples, N, N, D]) into a sparse matrix.

对于每个样本,我有 D NxN 个特征图.我想将每个 NxN 特征映射转换为一个稀疏矩阵,最大值映射为 1,所有其他映射为 0.

For each sample, I have D NxN feature maps. I want to convert each NxN feature map to a sparse matrix, with the maximum value mapped to 1 and all the others to 0.

我不想在运行时执行此操作,而是在 Graph 声明期间执行此操作(因为我需要使用生成的稀疏矩阵作为其他图形操作的输入),但我不明白如何获取索引以构建稀疏矩阵.

I do not want to do this at run time but during the Graph declaration (because I need to use the resulting sparse matrix as an input to other graph operations), but I do not understand how to get the indices to build the sparse matrix.

推荐答案

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

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

import numpy as np
import tensorflow as tf

# Make a tensor from a constant
a = np.reshape(np.arange(24), (3, 4, 2))
a_t = tf.constant(a)
# Find indices where the tensor is not zero
idx = tf.where(tf.not_equal(a_t, 0))
# Make the sparse tensor
# 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())
# Make a dense tensor back from the sparse one, only to check result is correct
dense = tf.sparse_tensor_to_dense(sparse)
# Check result
with tf.Session() as sess:
    b = sess.run(dense)
np.all(a == b)
>>> True

这篇关于来自密集张量 Tensorflow 的稀疏张量(矩阵)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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