代码之家  ›  专栏  ›  技术社区  ›  user3037172

K最近邻伪码?

  •  -3
  • user3037172  · 技术社区  · 11 年前

    所以我正在尝试对k近邻算法进行编码。我的函数的输入将是一组数据和一个要分类的样本。我只是想了解算法的工作原理。你们能告诉我我要做的事情的“伪代码”是否正确吗?

    kNN (dataset, sample){
    
       1. Go through each item in my dataset, and calculate the "distance" from that data item to my specific sample.
       2. Out of those samples I pick the "k" ones that are most close to my sample, maybe in a premade array of "k" items?
    
    }
    

    当我说“浏览我数据集中的每个项目”时,我会感到困惑。我是否应该遍历数据集中的每个CLASS并找到k个最近的邻居?然后从那里找出哪一个最接近我的样本,然后告诉我这个班级?

    第2部分的问题(ish)是使用这个算法,但没有样本。如何计算数据集的“准确性”?

    我真的在寻找宽泛的答案,而不是具体的细节,但任何有助于我理解的东西都是值得赞赏的。我在R。

    谢谢

    1 回复  |  直到 11 年前
        1
  •  11
  •   Mohsen Kamrani    11 年前

    伪代码应按以下方式更改:

    kNN (dataset, sample){
       1. Go through each item in my dataset, and calculate the "distance" 
       from that data item to my specific sample.
       2. Classify the sample as the majority class between K samples in 
       the dataset having minimum distance to the sample.
    }
    

    下图说明了这种伪代码。

    enter image description here

    假设数据集由两个类别A和B组成,分别显示为红色和蓝色,我们希望将K=5的KNN应用于样本,显示为绿色和紫色星。
    KNN计算每个测试样本与所有样本的距离,并找到与测试样本具有最小距离的五个相邻样本,并将多数类分配给测试样本。

    精确 :1-(错误分类的测试样本数量/测试样本数量)

    对于“R”中的实现,您可以看到 this this .