Skip to content

Commit e17051c

Browse files
author
Qi Chen
committed
provide distance convert between distance and cosine similarity
1 parent 4ba91f6 commit e17051c

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

AnnService/inc/Core/Common/DistanceUtils.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,17 +102,21 @@ namespace SPTAG
102102
return func(p1, p2, length);
103103
}
104104

105+
template<typename T>
105106
static inline float ConvertCosineSimilarityToDistance(float cs)
106107
{
107108
// Cosine similarity is in [-1, 1], the higher the value, the closer are the two vectors.
108109
// However, the tree is built and searched based on "distance" between two vectors, that's >=0. The smaller the value, the closer are the two vectors.
109110
// So we do a linear conversion from a cosine similarity to a distance value.
110-
return 1 - cs; //[1, 3]
111+
int base = Utils::GetBase<T>();
112+
return (1 - cs) * (base * base);
111113
}
112114

115+
template<typename T>
113116
static inline float ConvertDistanceBackToCosineSimilarity(float d)
114117
{
115-
return 1 - d;
118+
int base = Utils::GetBase<T>();
119+
return 1 - d / (base * base);
116120
}
117121
};
118122
template<typename T>

0 commit comments

Comments
 (0)