2017-04-11 20 views
5

Tôi có hai tensors chuẩn hóa và tôi cần tính toán độ tương tự cosin giữa các tensors này. Làm thế nào để tôi làm điều đó với TensorFlow?Cách tính độ tương tự Cosine giữa hai tensors?

cosine(normalize_a,normalize_b) 

    a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a") 
    b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b") 
    normalize_a = tf.nn.l2_normalize(a,0)   
    normalize_b = tf.nn.l2_normalize(b,0) 

Trả lời

9

này sẽ thực hiện công việc:

a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a") 
b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b") 
normalize_a = tf.nn.l2_normalize(a,0)   
normalize_b = tf.nn.l2_normalize(b,0) 
cos_similarity=tf.reduce_sum(tf.multiply(normalize_a,normalize_b)) 
sess=tf.Session() 
cos_sim=sess.run(cos_similarity,feed_dict={a:[1,2,3],b:[2,4,6]}) 

này in 0.99999988

+0

Cảm ơn bạn rất nhiều cho câu trả lời của bạn. Công thức tương tự cosin có được đơn giản hóa bằng cách chuẩn hóa đầu vào trước không? công thức của bạn dường như có ít thứ hơn từ Wikipedia https://en.wikipedia.org/wiki/Cosine_similarity – Matias

+3

Nếu bạn không chuẩn hóa trước, thì sau khi bạn tính toán sản phẩm bên trong a * b bạn phải chia cho sản phẩm các chỉ tiêu của a và b. Tuy nhiên, nếu bạn chuẩn hóa trước, bạn không cần phải làm điều đó. Điều này là do normalize_a = a/|| a || (và tương tự cho b). –

+0

tại sao không matmul? –

10

lần thay đổi. Với API TF mới nhất, điều này có thể được tính bằng cách gọi tf.losses.cosine_distance.

Ví dụ:

import tensorflow as tf 
import numpy as np 


x = tf.constant(np.random.uniform(-1, 1, 10)) 
y = tf.constant(np.random.uniform(-1, 1, 10)) 
s = tf.losses.cosine_distance(tf.nn.l2_normalize(x, 0), tf.nn.l2_normalize(y, 0), dim=0) 
print(tf.Session().run(s)) 

Tất nhiên, 1 - s là sự tương đồng cosin!

+0

tại sao 1-s tương tự cosin? –

+2

vì '' 's''' là khoảng cách cosin, không giống nhau. –

+0

'' '1-s''' là không cần thiết. Hàm này được gọi là khoảng cách, nhưng trả về sự giống nhau. Tôi nghĩ bởi vì nó nằm trong tf.losses. Hãy xem mã, tôi có thể sai. Dòng 274. thua = 1 - math_ops.reduce_sum (radial_diffs, axis = (dim,), keep_dims = True) https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/python/ops/losses/ loss_impl.py –

0

Bạn có thể bình thường hóa bạn vector hoặc ma trận như thế này:

[batch_size*hidden_num] 
states_norm=tf.nn.l2_normalize(states,dim=1) 
[batch_size * embedding_dims] 
embedding_norm=tf.nn.l2_normalize(embedding,dim=1) 
#assert hidden_num == embbeding_dims 
after mat [batch_size*embedding] 
user_app_scores = tf.matmul(states_norm,embedding_norm,transpose_b=True) 
Các vấn đề liên quan