Tensorflow:如何使tf.unique的返回值与输入相同

时间:2017-08-01 03:37:19

标签: python tensorflow

根据https://www.tensorflow.org/api_docs/python/tf/uniquetf.unique(x)会返回元组(y, idx),y的形状(?,)在构建时间内是未知的。无论如何我可以填y来匹配输入大小x吗?

例如,

# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]
y, idx = unique(x)
y ==> [1, 2, 4, 7, 8]
idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]

我想让y = [1,2,4,7,8,0,0,0,0]

3 个答案:

答案 0 :(得分:3)

调用tf.pad后,您可以使用tf.unique填充零。

x = tf.placeholder(tf.int32, shape=(None))
y, idx = tf.unique(x)
y = tf.pad(y,[[0,(tf.shape(x) - tf.shape(y))[0]]])

sess = tf.InteractiveSession()
print(sess.run(y, {x:np.random.randint(0,10, (10), dtype=np.int32)}))

答案 1 :(得分:1)

您需要单独处理问题。

y = [1, 2, 4, 7, 8]
idx = [0, 0, 1, 2, 2, 2, 3, 4, 4]

for ii in range(0, len(idx) - len(y)):
    y.append(0)

print(y)

输出

[1, 2, 4, 7, 8, 0, 0, 0, 0]

答案 2 :(得分:0)

使用set来查找唯一的..diff len并追加尾随0

data_dict_cleaned

输出

x = [1, 1, 2, 4, 4, 4, 7, 8, 8]
length = len(x)

print(length)
y = list(set(x))

print(y)
pad = length - len(list(set(x)))

for index in range(0,pad):
    y.append(0)


print(y)