美文网首页
MLA CH2 kNN code part

MLA CH2 kNN code part

作者: Mandy今天也沉迷学习 | 来源:发表于2020-03-08 00:29 被阅读0次

Python实例

kNN.py:

from numpy import *
import matplotlib
import matplotlib.pyplot as plt
import operator


def createDataSet():
    group = array([[3, 104], [2, 100], [1, 81], [101, 10], [99, 5], [98, 2]])
    names = ["CaliMan", "HNRD", "BW", "KL", "RS3000", "AII"]
    labels = ['R', 'R', 'R', 'A', 'A', 'A', 'A']
    return group, labels, names


def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    # Euclidian distance calculation
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistIndices = distances.argsort()  # 排序后的下标
    # print(sortedDistIndices)
    classCount = {}
    # voting
    for i in range(k):
        voteIlable = labels[sortedDistIndices[i]]
        classCount[voteIlable] = classCount.get(voteIlable, 0) + 1
    # sort the dictionary according to the second line
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def scatter(group, names):
    x=group[:, 0]
    y=group[:, 1]
    plt.scatter(x,y)
    for i in range(len(x)):
        plt.annotate(names[i], xy=(x[i], y[i]), xytext=(x[i]+1, y[i]+1))
    plt.show()

group, labels, names = createDataSet()
KNN = classify0([18, 90], group, labels, 3)
scatter(group, names)
print(KNN)

输出结果

result
  • 得出结果:“?”是Romance Movie

如何测试分类器(classifier)?

  • 不同的算法在不同的数据集上表现不同
  1. 将已知数据的答案对分类器进行隐藏,让分类器进行判断
  2. 得到分类器的 犯错率(error rate)=犯错的累计次数/总测试数

例子——>约会网站数据

Hellen出去约会的有三种人:她不喜欢的/ 她有一点喜欢的/ 她很喜欢的
周一到周五她愿意见有一点喜欢的人,周末更愿意见很喜欢的人
希望对未来的结果能够更加匹配

准备

数据包括:

  • 1000条数据
  • 每年的飞行长旅里程数
  • 打游戏的时间占比
  • 每周消耗的冰淇凌升数

手头无数据,详情过程请见P24-P

  • 标准化数据至(0,1)

测试

  • 前10%数据可以用来测试,90%用于训练。

例子——>手写识别系统

*binary image

相关文章

  • MLA CH2 kNN code part

    Python实例 kNN.py: 输出结果 得出结果:“?”是Romance Movie 如何测试分类器(clas...

  • MLA CH2 kNN theory part

    在这一部分书中的例子是电影的分类 kNN理论,如何用距离来分类 python导入数据 陷阱/隐患 2.1 以距离度...

  • kNN Code

    kNN是一种聚类算法,python的代码分类器函数思路即读取的数据为一个inX=[x,y,z]inX的第一列向量重...

  • CH2 kNN algorithm

    1.算法描述 邻近算法,或者说K最近邻(kNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最...

  • 重构与DSL

    OO makes code understandable by encapsulating moving part...

  • 精益编程:Write Lean Programs

    OO makes code understandable by encapsulating moving part...

  • 重构与函数

    OO makes code understandable by encapsulating moving part...

  • CPPYY include 和 load_libraries及动

    CPPYY Part II 动态特性 我们来实现一个简单的KNN算法 总结 cppyy生成的python 类可以...

  • C22.1-12 - Canadian electrical c

    下载地址: C22.1-12 - Canadian electrical code. Part I safety ...

  • CH2 Release

    @(Python)[CH2] Neil 完成 ch2 任务啦 任务成果地址 : city_weather 任务成果...

网友评论

      本文标题:MLA CH2 kNN code part

      本文链接:https://www.haomeiwen.com/subject/qvkldhtx.html