我有一个这样的张量:
-2.2
我需要将每行乘以其余行(按元素计算),然后对结果求和。
第一行完成后,我们将处理第二行以及其余行,然后...
结果将是这样的:它将是tf_docs = tf.constant([[0, 2, 1],
[1, 2, 2],
[2, 1, 3],
[5, 2, 2]], dtype=tf.int32)
,因为我们有4行
4*4
让我解释result_tf =[[0, 6, 5, 6 ],
[6, 0, 10, 13],
[5, 10, 3, 18],
[6, 13, 18, 0]]
中的每个元素(矩阵是对称的。
第一行:
result_tf
第二行:
0*1 + 2*2 + 1*2 = 6
0*2 + 2*1 + 1*3 = 5
0*5 + 2*2 + 1*2 = 6
第三行:
1*2 + 2*1 + 2*3 = 10
1*5 + 2*2 + 2*2 = 13
这些就是我形成矩阵上侧的方式。
然后,diag中的值是:
2*5 + 1*2 + 3*2 = 18
在任何列中都没有(0,0)
,所以co-occurred
0
在任何列中都没有(1,1)
,所以co-occurred
0
在第二栏中有(2,2)
时间,在第三栏中有co-occurred 2
,因此1 time
3
没有在任何列中同时出现,所以(3,3)
我觉得这需要比了解技术更多的创造力来解决。 (从字面上看,如果您了解共现的概念,那么我将在同一矩阵上计算共现)
我所做的:
我可以使用for循环轻松地做到这一点。但是我需要完成张量流操作,并且找不到类似的问题。 我也在考虑使用collect每次获取指定的行并将其合并。但是这种方法不是动态的,而且我的行和列都比这个大,所以这种解决方案将不可行
答案 0 :(得分:1)
这是一种实现方法:
import tensorflow as tf
tf_docs = tf.constant([[0, 2, 1],
[1, 2, 2],
[2, 1, 3],
[5, 2, 2]], dtype=tf.int32)
# Non-diagonal elements
nondiag = tf.matmul(tf_docs, tf_docs, transpose_b=True)
# Compute diagonal
r = tf.range(tf.shape(tf_docs, out_type=tf_docs.dtype)[0])
# Compare each index against each value
cmp = tf.equal(tf.expand_dims(tf_docs, axis=-1), r)
# Count appearances of each index in each column
count = tf.math.count_nonzero(cmp, axis=0, dtype=tf_docs.dtype)
# Sum number of appearances over one
diag = tf.reduce_sum(tf.maximum(count - 1, 0), axis=0)
# Set diagonal elements
result_tf = tf.linalg.set_diag(nondiag, diag)
print(result_tf.numpy())
# [[ 0 6 5 6]
# [ 6 0 10 13]
# [ 5 10 3 18]
# [ 6 13 18 0]]