2017-06-01 570 views
0

我需要计算cosine_distance迭起,tf.losses.cosine_distance返回一个标张量,所以我做了这样的:如何有效计算两个向量之间的距离?

x # a tensor list 
    y # a tensor list 
    for i in x: 
    for j in y: 
     distance = tf.losses.cosine_distance(i, j, dim=0) 

这种方法使得图形过大和装载的程序太慢。我怎样才能优化它?

回答

1

循环在张量流中不好。 我假设在张量列出了所有的向量长度相等

的试试这个:

x_t = tf.stack(x) 
y_t = tf.stack(y) 
prod = tf.matmul(x_t, y_t, transpose_b=True) 
x_len = tf.sqrt(tf.reduce_sum(tf.matmul(x_t, x_t), axis=0)) 
y_len = tf.sqrt(tf.reduce_sum(tf.matmul(y_t, y_t), axis=0)) 
cosine_dist = prod/tf.matmul(x_len, y_len, transpose_b=True) 
相关问题