如何正確獲取影像嵌入與另一個影像嵌入串列/組的距離?
我有一個預訓練模型,用于從影像中提取嵌入,我想獲得影像與其他一些影像的距離,即
Embedding (1028,) against Embedding (5, 1028)
我正在嘗試做一個影像相似性實驗,其中我使用 Tensorflow 的余弦相似性度量來計算兩個嵌入之間的距離,并且它在 1 對 1 計算中運行良好,即
Embedding_1 = (1028,)
Embedding_2 = (1028,)
metrics.CosineSimilarity(Embedding_1, Embedding_2)
但我無法弄清楚如何在 1 到 N 距離計算中做到這一點。
Embedding_1 = (1028,)
Embedding_Group = [(1028,),(1028,),(1028,),(1028,),(1028,)]
uj5u.com熱心網友回復:
這可以通過廣播來完成。在這種情況下,迭代影像并計算每個單獨對的距離是個壞主意,因為它不會被并行化(除非你知道如何自己做)。
import tensorflow as tf
embedding = tf.constant([1., 1.]) # your shape here is (1028,) instead of (2,)
embedding_group = tf.constant([[1., 1.], [1., 2.], [0., 1.]]) # your shape here is (5, 1028) instead of (3, 2)
norm_embedding = tf.nn.l2_normalize(embedding[None, ...], axis=-1)
norm_embedding_group = tf.nn.l2_normalize(embedding_group, axis=-1)
similarity = tf.reduce_sum(norm_embedding * norm_embedding_group, axis=-1) # cosine similarity of same shape as number of samples
print(norm_embedding.numpy())
print(norm_embedding_group.numpy())
print(similarity.numpy())
# [[0.7071067 0.7071067]]
# [[0.7071067 0.7071067 ]
# [0.44721356 0.8944271 ]
# [0. 1. ]]
# [0.9999998 0.94868314 0.7071067 ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363849.html
上一篇:InvalidArgumentError:ConcatOp:使用Conv2D預測X_test時,輸入的維度應該匹配-為什么?
