计算图像嵌入与一组图像嵌入的距离
Computing the distance of an image embedding against a group of image embeddings
如何正确获取图像嵌入与另一个图像嵌入的 list/group 的距离?
我有一个预训练模型,我用它来从图像中提取嵌入,我想获得图像与其他少数图像的距离,即
Embedding (1028,) against Embedding (5, 1028)
我正在尝试做一个图像相似性实验,其中我使用 Tensorflow 的余弦相似性度量来计算两个嵌入之间的距离,并且它在一对一计算中效果很好,即
Embedding_1 = (1028,)
Embedding_2 = (1028,)
metrics.CosineSimilarity(Embedding_1, Embedding_2)
但我不知道如何计算 1 对 N 的距离。
Embedding_1 = (1028,)
Embedding_Group = [(1028,),(1028,),(1028,),(1028,),(1028,)]
可以用 broadcasting 完成。在这种情况下,为每一对迭代图像和计算距离是个坏主意,因为它不会被并行化(除非你知道如何自己做)。
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 ]
如何正确获取图像嵌入与另一个图像嵌入的 list/group 的距离?
我有一个预训练模型,我用它来从图像中提取嵌入,我想获得图像与其他少数图像的距离,即
Embedding (1028,) against Embedding (5, 1028)
我正在尝试做一个图像相似性实验,其中我使用 Tensorflow 的余弦相似性度量来计算两个嵌入之间的距离,并且它在一对一计算中效果很好,即
Embedding_1 = (1028,)
Embedding_2 = (1028,)
metrics.CosineSimilarity(Embedding_1, Embedding_2)
但我不知道如何计算 1 对 N 的距离。
Embedding_1 = (1028,)
Embedding_Group = [(1028,),(1028,),(1028,),(1028,),(1028,)]
可以用 broadcasting 完成。在这种情况下,为每一对迭代图像和计算距离是个坏主意,因为它不会被并行化(除非你知道如何自己做)。
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 ]