9 python graph sparse-matrix autoencoder tensorflow
我正在创建一个卷积稀疏自动编码器,我需要将一个充满值(其形状[samples, N, N, D])的4D矩阵转换为稀疏矩阵.
对于每个样本,我有D NxN特征映射.我想将每个NxN特征映射转换为稀疏矩阵,最大值映射为1,其他所有映射为0.
我不想在运行时这样做但在Graph声明期间(因为我需要使用生成的稀疏矩阵作为其他图形操作的输入),但我不明白如何获得索引来构建稀疏矩阵.
jde*_*esa 15
您可以使用tf.where和tf.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4459 次 |
| 最近记录: |