我有一个张量如下:
arr = [[1.5,0.2],[2.3,0.1],[1.3,0.21],[2.2,0.09],[4.4,0.8]]
我想收集第一个元素的差异在0.3以内、第二个元素的差异在0.03以内的小数组。 例如[1.5,0.2]和[1.3,0.21]应该属于同一类别。它们的第一个元素的差异是0.2<0.3,第二个元素的差异是0.01<0.03。
我想要一个像这样的张量
arr = {[[1.5,0.2],[1.3,0.21]],[[2.3,0.1],[2.2,0.09]]}
如何在 tensorflow 中做到这一点? Eager 模式没问题。
我发现了一种有点丑陋且缓慢的方法:
samples = np.array([[1.5,0.2],[2.3,0.1],[1.3,0.2],[2.2,0.09],[4.4,0.8],[2.3,0.11]],dtype=np.float32)
ini_samples = samples
samples = tf.split(samples,2,1)
a = samples[0]
b = samples[1]
find_match1 = tf.reduce_sum(tf.abs(tf.expand_dims(a,0) - tf.expand_dims(a,1)),2)
a = tf.logical_and(tf.greater(find_match1, tf.zeros_like(find_match1)),tf.less(find_match1, 0.3*tf.ones_like(find_match1)))
find_match2 = tf.reduce_sum(tf.abs(tf.expand_dims(b,0) - tf.expand_dims(b,1)),2)
b = tf.logical_and(tf.greater(find_match2, tf.zeros_like(find_match2)),tf.less(find_match2, 0.03*tf.ones_like(find_match2)))
x,y = tf.unique(tf.reshape(tf.where(tf.logical_or(a,b)),[1,-1])[0])
r = tf.gather(ini_samples, x)
tensorflow还有更优雅的功能吗?
最佳答案
您无法获得由不同大小的向量“组”组成的结果。相反,您可以创建一个“组 ID”张量,根据您的标准将每个向量分类为一个组。让这变得更复杂的部分是你必须将组与公共(public)元素“融合”,我认为这只能通过循环来完成。这段代码做了类似的事情:
import tensorflow as tf
def make_groups(correspondences):
# Multiply each row by its index
m = tf.to_int32(correspondences) * tf.range(tf.shape(correspondences)[0])
# Pick the largest index for each row
r = tf.reduce_max(m, axis=1)
# While loop accounts for transitive correspondences
# (e.g. if A and B go toghether and B and C go together, then A, B and C go together)
# The loop makes sure every element gets the largest common group id
r_prev = -tf.ones_like(r)
r, _ = tf.while_loop(lambda r, r_prev: tf.reduce_any(tf.not_equal(r, r_prev)),
lambda r, r_prev: (tf.gather(r, r), tf.identity(r)),
[r, r_prev])
# Use unique indices to make sequential group ids starting from 0
return tf.unique(r)[1]
# Test
with tf.Graph().as_default(), tf.Session() as sess:
arr = tf.constant([[1.5 , 0.2 ],
[2.3 , 0.1 ],
[1.3 , 0.21],
[2.2 , 0.09],
[4.4 , 0.8 ],
[1.1 , 0.23]])
a = arr[:, 0]
b = arr[:, 0]
cond = (tf.abs(a - a[:, tf.newaxis]) < 0.3) | (tf.abs(b - b[:, tf.newaxis]) < 0.03)
groups = make_groups(cond)
print(sess.run(groups))
# [0 1 0 1 2 0]
因此在这种情况下,这些组将是:
[1.5, 0.2]
、[1.3, 0.21]
和[1.1, 0.23]
[2.3, 0.1]
和[2.2, 0.09]
[4.4, 0.8]
关于python - tensorflow 从列表中收集相似的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288704/