IndexFlat原理比较简单,把add进来的原始向量,全部保存起来。
在检索时,query向量和索引中的所有的原始向量求距离
这种暴力批量的方式,性能非常差,效果是最好的。
void IndexFlat::add (idx_t n, const float *x) {
xb.insert(xb.end(), x, x + n * d);
ntotal += n; ///所有向量
}
void IndexFlat::reset() {
xb.clear();
ntotal = 0;
}
/*n:向量个数, x:向量值, k:返回个数, distances:返回值, labels:返回值*/
void IndexFlat::search (idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
// we see the distances and labels as heaps
if (metric_type == METRIC_INNER_PRODUCT) {
float_minheap_array_t res = {
size_t(n), size_t(k), labels, distances};
knn_inner_product (x, xb.data(), d, n, ntotal, &res); ///向量内积
} else if (metric_type == METRIC_L2) {
float_maxheap_array_t res = {
size_t(n), size_t(k), labels, distances};
knn_L2sqr (x, xb.data(), d, n, ntotal, &res); ///距离公式
} else {

本文介绍了IndexFlat索引的基本原理,即原始向量的直接存储和检索时的暴力批量计算。重点讲述了其效率低下问题,并提到了内积、L2距离和其他额外度量的搜索方法。为了改善性能,后续可能探讨了优化策略和替代算法。
最低0.47元/天 解锁文章
9513





