首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用nanoflann的奇异行为

使用nanoflann的奇异行为
EN

Stack Overflow用户
提问于 2020-12-02 06:49:35
回答 1查看 62关注 0票数 1

在使用nanoflann-library进行基于KDTrees的k近邻搜索时,我遇到了一个非常奇怪的行为。我的代码是一组简单的查询:

代码语言:javascript
复制
#include <vector>
#include <iostream>
#include <nanoflann.hpp>
#include <eigen3/Eigen/Dense>

using Eigen::MatrixX3d;
using Eigen::Vector3d;

using nanoflann::KNNResultSet;
using nanoflann::SearchParams;
using kdt = nanoflann::KDTreeEigenMatrixAdaptor<MatrixX3d, 3, nanoflann::metric_L2>;

int main()
{
    // Create simple matrix
    MatrixX3d matrix(10, 3);
    for(unsigned int i = 0; i < 10; i++)
    {
        double f_i = static_cast<double>(i);
        matrix.row(i) = Vector3d(f_i, 0, 0);
    }

    // Create test points
    std::vector<Vector3d> test_vecs;
    for(unsigned int i = 0; i < 10; i++)
    {
        double f_i = static_cast<double>(i);
        test_vecs.push_back(Vector3d(f_i, f_i, f_i));
    }
    
    // Result buffer
    double distance;
    size_t index;
    KNNResultSet<double> result_set(1);
    result_set.init(&index, &distance);
    SearchParams sp;
    // KDTree
    kdt matrix_index(3, std::ref(matrix), 10);
    matrix_index.index->buildIndex();

    //Query points backwards
    for(int i = 9; i >= 0; i--)
    {
        Vector3d curr_vec = test_vecs.at(i);
        matrix_index.index->findNeighbors(result_set, &curr_vec[0], sp);
        std::cout << i << std::endl;
        std::cout << index << " " << distance << std::endl << std::endl;
    }

    // Query points forwards
    for(unsigned int i = 0; i < 10; i++)
    {
        Vector3d curr_vec = test_vecs.at(i);
        matrix_index.index->findNeighbors(result_set, &curr_vec[0], sp);
        std::cout << i << std::endl;
        std::cout << index << " " << distance << std::endl << std::endl;
    }
}

向后查询(BQ)返回预期的结果。然而,正向查询(FQ)只产生零(索引和距离)。FQ似乎也完全打破了KDTree。如果更改两个查询(最后两个for循环)的顺序,以便在BQ之前执行FQ,那么这两个查询现在都将只生成0。

为什么会发生这种行为,以及如何规避它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-02 13:28:38

结果集看起来是有状态的-它总是向您显示所有点中最接近的整体邻居。例如,如果您从5循环到10,那么每次迭代都会得到5 50

在每次迭代中重新初始化结果集,您将获得所需的行为:

代码语言:javascript
复制
result_set.init(&index, &distance);
matrix_index.index->findNeighbors(result_set, &curr_vec[0], sp);

演示:https://godbolt.org/z/s5f1jq

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65099735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档