2017-06-01 573 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) 
相關問題