KNN算法思想与实现

时间:2022-02-21 13:15:54

第二章 k近邻

2.1 算法描述

(1)采用测量不同特征值之间的距离进行分类

优点:对异常点不敏感,精度高,无数据输入设定

缺点:空间,计算复杂度高

适合数据:标称与数值

(2)算法的工作原理:

基于已有的带有标签的训练数据,计算出需要预测的数据与每个训练数据之间的距离,找到其中距离最近的k个数据,根据这k数据中数量最多的类来决定测试数据的类别

(3)算法的类别

该算法属于有监督学习,用于分类,因此它的目标变量是离散的

(4)算法的一般流程:

1.收集数据

2.准备数据

3.分析数据

4.测试算法

5.使用算法

2.2算法实现过程

(1)获取数据

KNN算法思想与实现

  (2)KNN算法

from numpy import *
import operator # this KNN matrix col is 3
# in order to create data
def createDataSet():
group = array([[1.0, 1.1], [1.0, 1.0], [0.0, 0.0], [0.0, 0.1]])
lables = ['A', 'A', 'B', 'B']
return group, lables # main algorithm
def classify0(inx, dataSet, lables, k):
datasetSize = dataSet.shape[0]
diffmat = tile(inx, (datasetSize, 1)) - dataSet
sqdiffmat = diffmat**2
sqDistance = sqdiffmat.sum(axis=1)
distance = sqDistance**0.5
sortedDistance = distance.argsort()
classcount = {}
for i in range(k):
votelabel = lables[sortedDistance[i]]
classcount[votelabel] = classcount.get(votelabel, 0) + 1
sortedclasscount = sorted(classcount.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedclasscount[0][0] # read the txt data file
def file2matrix(filename):
fr = open(filename)
arraylines = fr.readlines()
numberoflines = len(arraylines)
returnmatrix = zeros((numberoflines, 3)) # you can change the col
clasavector = []
index = 0
for line in arraylines:
line = line.strip()
listformline = line.split('\t')
returnmatrix[index, :] = listformline[0:3] # you should change the col
clasavector.append(int(listformline[-1]))
index += 1
return returnmatrix, clasavector # normalize the data
def autonorm(dataset):
minval = dataset.min(0)
maxval = dataset.max(0)
ranges = maxval - minval
datasetsize = dataset.shape[0]
normdataset = dataset - tile(minval, (datasetsize, 1))
normdataset = normdataset/tile(ranges, (datasetsize, 1))
return normdataset, ranges, minval def datingclasstest(filename):
horatio = 0.1
dataset, lableset = file2matrix(filename)
noramdataset, ranges, minval = autonorm(dataset)
col = dataset.shape[0]
test = int(col*horatio)
errorcount = 0.0
for i in range(col):
classlable = classify0(noramdataset[i, :], noramdataset[test:col, :], lableset[test:col], 3)
if classlable != lableset[i]:
errorcount += 1
error = errorcount / float(col)
print error

  (3)dating应用程序

import KNN
from numpy import * def classifyperson():
returnlist = ['not at all', 'in small doses', 'in large doses']
game = float(raw_input("the percentage of playing video game"))
fly = float(raw_input("the num of the flier mail"))
icecream = float(raw_input("the num of icecream every weak"))
person = array([game, fly, icecream])
dataset,datalable = KNN.file2matrix("F:data/machinelearninginaction/Ch02/datingTestSet2.txt")
normdataset, ranges, minval=KNN.autonorm(dataset)
classifierresult =KNN.classify0((person - minval)/ranges, normdataset, datalable, 3)
print "you will like him %s" % returnlist[classifierresult-1]

  (4)手写识别程序

import KNN
from os import listdir
from numpy import * # change the 32*32 to vector
def image2vertor(filename):
fr = open(filename)
imagevertor = zeros((1, 1024))
for i in range(32):
line = fr.readline()
for j in range(32):
imagevertor[0, i*32+j] = int(line[j])
return imagevertor
testvector = image2vertor("F:data/machinelearninginaction/Ch02/digits/testDigits/0_13.txt") def handwritingtest():
hwlables = [] # record the lable
filename = listdir("F:data/machinelearninginaction/Ch02/digits/trainingDigits/")
filenum = len(filename)
dataset = zeros((filenum, 1024))
for i in range(filenum):
filenamestr = filename[i].split(".")[0]
filelable = int(filenamestr.split('_')[0])
hwlables.append(filelable)
filepath = "F:data/machinelearninginaction/Ch02/digits/trainingDigits/" + filename[i]
data = image2vertor(filepath)
dataset[i, :] = data
testfile = listdir("F:data/machinelearninginaction/Ch02/digits/testDigits/")
testfilenum = len(testfile)
for j in range(testfilenum):
testfilestr = testfile[j].split('.')[0]
testfilelable =int(testfilestr.split('_')[0])
testdilepath = "F:data/machinelearninginaction/Ch02/digits/testDigits/" + testfile[j]
testdata = image2vertor(testdilepath)
classname = KNN.classify0(testdata, dataset, hwlables, 3)
error = 0.0
if classname == testfilelable:
error += 1
print "we think it is %d, the real is %d" % (classname, testfilelable)
print "the num of error is %d " % error
print "the error rate is %f" % (error/float(testfilenum)) handwritingtest()

KNN算法思想与实现的更多相关文章

  1. 机器学习之KNN算法思想及其实现

    从一个例子来直观感受KNN思想 如下图 , 绿色圆要被决定赋予哪个类,是红色三角形还是蓝色四方形?如果K=3,由于红色三角形所占比例为2/3,绿色圆将被赋予红色三角形那个类,如果K=5,由于蓝色四方形 ...

  2. Python 手写数字识别-knn算法应用

    在上一篇博文中,我们对KNN算法思想及流程有了初步的了解,KNN是采用测量不同特征值之间的距离方法进行分类,也就是说对于每个样本数据,需要和训练集中的所有数据进行欧氏距离计算.这里简述KNN算法的特点 ...

  3. 机器学习【三】k-近邻(kNN)算法

    一.kNN算法概述 kNN算法是用来分类的,其依据测量不同特征值之间的距离,其核心思想在于用距离目标最近的k个样本数据的分类来代表目标的分类(这k个样本数据和目标数据最为相似).其精度高,对异常值不敏 ...

  4. KNN算法原理(python代码实现)

    kNN(k-nearest neighbor algorithm)算法的核心思想是如果一个样本在特征空间中的k个最相邻的样本中的大多数属于某一个类别,则该样本也属于这个类别,并具有这个类别上样本的特性 ...

  5. 【Machine Learning】KNN算法虹膜图片识别

    K-近邻算法虹膜图片识别实战 作者:白宁超 2017年1月3日18:26:33 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...

  6. 机器学习&数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)

    前言: 找工作时(IT行业),除了常见的软件开发以外,机器学习岗位也可以当作是一个选择,不少计算机方向的研究生都会接触这个,如果你的研究方向是机器学习/数据挖掘之类,且又对其非常感兴趣的话,可以考虑考 ...

  7. kNN算法python实现和简单数字识别

    kNN算法 算法优缺点: 优点:精度高.对异常值不敏感.无输入数据假定 缺点:时间复杂度和空间复杂度都很高 适用数据范围:数值型和标称型 算法的思路: KNN算法(全称K最近邻算法),算法的思想很简单 ...

  8. 数据挖掘之KNN算法(C#实现)

    在十大经典数据挖掘算法中,KNN算法算得上是最为简单的一种.该算法是一种惰性学习法(lazy learner),与决策树.朴素贝叶斯这些急切学习法(eager learner)有所区别.惰性学习法仅仅 ...

  9. KNN算法与Kd树

    最近邻法和k-近邻法 下面图片中只有三种豆,有三个豆是未知的种类,如何判定他们的种类? 提供一种思路,即:未知的豆离哪种豆最近就认为未知豆和该豆是同一种类.由此,我们引出最近邻算法的定义:为了判定未知 ...

随机推荐

  1. [leetcode]Binary Tree Maximum Path Sum

    Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and ...

  2. mysql pid文件

    mysql pid文件记录的是当前mysqld进程的pid. 通过Mysqld_safe启动mysql时,mysqld_safe会检查pid文件,未指定PID文件时,pid文件默认名为$DATADIR ...

  3. UML时序图总结

    前言 在我的工作中,用的最多的就是时序图了.可能由于工作的原因,我也是最喜欢画时序图了,很清楚,很明了,什么时候发送什么消息,到达什么状态,一下子就展示在你的脑海里,对于消息驱动的程序来说,是再好不过 ...

  4. 简单的后台数据和前台数据交互.net

    最近忙着做POS项目,心血来来潮写了点小项目. 更具要求是随机显示数据并且产生的数据是可以控制的.前台交互显示能够倒叙,切每次只显示一条,页面不能超过20条超过的部分做删除. 我先展示一下前台的代码, ...

  5. poj 2723 二分+2-sat判定

    题意:给出n对钥匙,每对钥匙只能选其中一个,在给出每层门需要的两个钥匙,只要一个钥匙就能开门,问最多能到哪层. 思路:了解了2-SAT判定的问题之后主要就是建图的问题了,这里建图就是对于2*n个钥匙, ...

  6. 如何创建线程第二种实现Runnable接口

    package TestException; public class test5 { public static void main(String[] args) { Test6 s1 = new ...

  7. [Spark]What's the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

    From the answer here, spark.sql.shuffle.partitions configures the number of partitions that are used ...

  8. Android学习笔记九:Service

    一:Service是什么 Service,服务.一般用于提供需要在后台长期运行的服务(如复杂计算.下载等等耗时任务),其特点是长生命周期的.没有用户界面.在后台运行的. 二:Service的生命周期方 ...

  9. mysql中删除binlog的方法?mysql中如何删除binlog?

    需求描述: 在mysql中如何删除binlog,因为随着数据库的运行,mysql中产生的binlog会越来越大,有可能把磁盘撑爆了,所以记录下删除 binlog的方法. 操作过程: 1.通过系统参数控 ...

  10. Linux软件管理器(如何使用软件管理器来管理软件)2---安装及管理Linux应用程序

    安装及管理Linux应用程序 Linux应用程序的组成1.普通的可执行程序文件,一般保存在/usr/bin目录中,普通用户即可执行.2.服务器程序.管理程序文件,一般保存在/usr/sbin目录中,需 ...