• K-近邻算法


    废话不多说,直接放码过来。

     1 from numpy import *
     2 import operator
     3 def createDataSet () :
     4     group = array([[0.5,0.5],[0.9,0.9],[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])#创建数组
     5     labels = ['c','A','A','A','B','B'] #列表
     6     return group,labels
     7     
     8 def classify0(inX,dataSet,labels,k):
     9     dataSetSize = dataSet.shape[0]     #dataSet[0] 中有几个元素  答案是4
    10     diffMat = tile(inX,(dataSetSize,1)) - dataSet     
    11     sqDiffMat = diffMat**2    #计算出来距离
    12     sqDistances = sqDiffMat.sum(axis=1) #将一个小数组合并的距离的平方
    13     distances = sqDistances**0.5  #得到具体的距离
    14     sortedDistIndicies = distances.argsort() #根据索引值进行排序
    15     print(sortedDistIndicies)
    16     classCount = {}
    17     
    18     
    19     for i in range(k):
    20         voteIlabel = labels[sortedDistIndicies[i]]   #取出来最小值
    21      #   print(voteIlabel)
    22         classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 # 记录每组分类的案例数。
    23     #    print(classCount)
    24         sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse = True)  # 按照案例数的大小进行排序。
    25     return sortedClassCount[0][0]
    26     
    27     

      我看得是《机器学习实战》这一本书,我坑在这几行代码的地方是    选取与当前点距离最小的K各店,确定K各点所在类别的出现频率,返回这些类别中出现最多的类别就是想要点的类别。

      就这样,挺有意思的。

  • 相关阅读:
    C# 中的栈和堆
    C# 中的基本数值类型
    多个 .NET 框架
    简单介绍托管执行和 CLI
    C# 控制台输入和输出
    在 C# 中使用变量
    C# 语法基础
    LeetCode 1482. 制作 m 束花所需的最少天数
    C# 基础(更新中)
    圆形靶内的最大飞镖数量
  • 原文地址:https://www.cnblogs.com/A-FM/p/6139178.html
Copyright © 2020-2023  润新知