来自密集的Tensorflow的稀疏矩阵

问题描述 投票:8回答:2

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

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

我不想在运行时这样做但在Graph声明期间(因为我需要使用生成的稀疏矩阵作为其他图形操作的输入),但我不明白如何获得索引来构建稀疏矩阵。

python graph tensorflow sparse-matrix autoencoder
2个回答
14
投票

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

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

2
投票

将密集numpy数组转换为tf.SparseTensor的简单代码:

def denseNDArrayToSparseTensor(arr):
  idx  = np.where(arr != 0.0)
  return tf.SparseTensor(np.vstack(idx).T, arr[idx], arr.shape)
© www.soinside.com 2019 - 2024. All rights reserved.