Tensorflow / keras - 在张量中找到唯一元素的位置

时间:2018-06-07 15:51:54

标签: tensorflow keras

我试图在二维张量中找到所有不同值的位置。假设我有以下张量:

spMap4x4 = tf.Variable([[1, 2, 2, 2], [1, 1, 2, 3], [1, 3, 3, 3], [1, 1, 3, 3]])

我希望找到元素的位置等于1,然后元素的位置等于2,最后,元素的位置等于3,而不事先知道这些值。

我的想法是在将spMap4x4重新塑造为1-D张量后使用“tf.unique_with_counts”:

spMapFlatten = tf.reshape(spMap4x4, [-1])
y, idx, count = tf.unique_with_counts(spMapFlatten)

然后,使用“tf.where”来获得我需要的位置。例如:

a = tf.where(tf.equal(spMap4x4, y[0])
K.eval(a) 

这里给出:

a = [[0 0]
     [1 0]
     [1 1]
     [2 0]
     [3 0]
     [3 1]]

问题是,如何在不知道这些值是什么的情况下为y中的所有不同值执行此操作?这将包含在keras层中,因此,我需要一个通用的解决方案。

1 个答案:

答案 0 :(得分:0)

想到的解决方案是使用tf.dynamic_partition(),但它需要您知道您可能拥有的最大分区数(即输入张量中唯一值的最大数量):

import tensorflow as tf

spMap4x4 = tf.constant([[1, 2, 2, 2], [1, 1, 2, 3], [1, 3, 3, 3], [1, 1, 3, 3]])

# Requirement: knowing the max number of different values (partitions) your tensor may have
max_diff_values = 4

spMap4x4_shape = tf.shape(spMap4x4)
# Getting unique values and their reverse indices / partitions:
unique_val, unique_idx = tf.unique(tf.reshape(spMap4x4, [-1]))
unique_idx = tf.reshape(unique_idx, spMap4x4_shape)

# Building an index matrix:
idx_cols, idx_rows = tf.meshgrid(tf.range(spMap4x4_shape[0]), tf.range(spMap4x4_shape[1]))
idx_grid = tf.stack([idx_rows, idx_cols], -1)

# Partitioning the index matrix according to the unique values' partitions:
partitioned_idx = tf.dynamic_partition(idx_grid, unique_idx, num_partitions=max_diff_values)

with tf.Session() as sess:
    print(sess.run(partitioned_idx))
    # [array([[0, 0],
    #         [1, 0],
    #         [1, 1],
    #         [2, 0],
    #         [3, 0],
    #         [3, 1]], dtype=int32),
    #  array([[0, 1],
    #         [0, 2],
    #         [0, 3],
    #         [1, 2]], dtype=int32), 
    #  array([[1, 3],
    #         [2, 1],
    #         [2, 2],
    #         [2, 3],
    #         [3, 2],
    #         [3, 3]], dtype=int32), 
    #  array( [], shape=(0, 2), dtype=int32)]