感谢 FinleyGibson 提供 Numpy 解决方案和一些有用的 TensorFlow 指针!这是我在 TF 中使用tf.unique_with_counts() 和tf.segment_sum() 的解决方案:
罢工>
x = tf.constant([
[1., 0.9],
[2., 0.7],
[1., 0.7],
[3., 0.4],
[4., 0.8]
], dtype=tf.float32)
with tf.Session() as sess:
y, idx, y_counts = tf.unique_with_counts(x[:, 0])
idx_sorted = tf.sort(idx, axis=-1, direction='ASCENDING')
score_sum = tf.segment_sum(x[:, 1], idx_sorted)
result = tf.stack((y, score_sum), axis=1)
print(sess.run(result))
[[1. 1.5999999]
[2. 0.7 ]
[3. 0.4 ]
[4. 0.8 ]]
编辑:
- 似乎上述解决方案没有正确排序行/列对。这是固定版本。
with tf.Session() as sess:
x = tf.constant([
[2., 0.7],
[1., 0.1],
[3., 0.4],
[4., 0.8],
[1., 0.9]], dtype=tf.float32)
def matrix_sort(a, col):
return tf.gather(a, tf.nn.top_k(-a[:, col], k=a.get_shape()[0].value).indices)
sorted_x = matrix_sort(matrix_sort(x, 1), 0)
labels = sorted_x[:, 0]
scores = sorted_x[:, 1]
y, idx, y_counts = tf.unique_with_counts(labels)
score_sum = tf.segment_sum(scores, idx)
result = tf.stack((y, score_sum), axis=1)
print(sess.run(result))
[[1. 1. ]
[2. 0.7]
[3. 0.4]
[4. 0.8]]