机器学习实战(k-近邻算法)

2024-08-25 07:58

本文主要是介绍机器学习实战(k-近邻算法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

给定训练数据样本和标签,对于某测试的一个样本数据,选择距离其最近的k个训练样本,这k个训练样本中所属类别最多的类即为该测试样本的预测标签。简称kNN。通常k是不大于20的整数,这里的距离一般是欧式距离。

K最近邻(k-Nearest Neighbour,KNN)分类算法,是一个理论上比较成熟的方法,也是最简单的机器学习算法之一。该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。
用官方的话来说,所谓K近邻算法,即是给定一个训练数据集,对新的输入实例,在训练数据集中找到与该实例最邻近的K个实例(也就是上面所说的K个邻居), 这K个实例的多数属于某个类,就把该输入实例分类到这个类中。
下面是机器学习实战书中一些代码的实现:

其中包含使用k-邻近算法改进约会网站配对效果代码和手写识别系统的代码:

#coding=UTF8 
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
import operator
from os import listdirdef createDataSet():group = array([[3,104],[2,100],[1,81],[101,10],[99,5]]) #训练集labels = ['affectional film','affectional film','affectional film','action movie',"action movie"]return group,labelsdef classify0(inX,dataSet,labels,k):dataSetSize = dataSet.shape[0]diffMat = tile(inX, (dataSetSize,1)) - dataSetsqDiffMat = diffMat ** 2; #diffMat ^ 2sqDistances = sqDiffMat.sum(axis=1) #将矩阵的每一行相加比如[[2,1,3],[1,1,1]]结果为[6,3]distances = sqDistances ** 0.5 #sqDistances ^ (1/2)sortedDistIndicies = distances.argsort()classCount = {}for i in range(k):voteIlabel = labels[sortedDistIndicies[i]]classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)   #获取对象的第1个域的值return sortedClassCount[0][0]def file2matrix(filename):fr = open(filename)numberOfLines = len(fr.readlines())         #get the number of lines in the filereturnMat = zeros((numberOfLines,3))        #prepare matrix to returnclassLabelVector = []                       #prepare labels return   fr = open(filename)index = 0for line in fr.readlines():line = line.strip()listFromLine = line.split('\t')returnMat[index,:] = listFromLine[0:3]classLabelVector.append(int(listFromLine[-1]))index += 1return returnMat,classLabelVectordef autoNorm(dataSet):minVals = dataSet.min(0) #参数0从当前列选取最小值maxVals = dataSet.max(0) #同上ranges = maxVals - minValsnormDataSet = zeros(shape(dataSet)) #创建规模为dataSet的零矩阵m = dataSet.shape[0] #行normDataSet = dataSet - tile(minVals, (m,1)) #m行1列的minValsnormDataSet = normDataSet / tile(ranges, (m,1))return normDataSet,ranges,minValsdef datingClassTest():hoRatio = 0.10datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')normMat,ranges,minVals = autoNorm(datingDataMat)m = normMat.shape[0] #行numTestVecs = int(m * hoRatio) #算出测试数据errorCount = 0.0for i in range(numTestVecs):classifierResult = classify0(normMat[i,:], normMat[numTestVecs:m,:], datingLabels[numTestVecs:m], 3) #@param1:读入每行的数据,@param2:样本数据,因为测试数据是0-numTestVecsprint "the classifier came back with: %d,the real answer is : %d" % (classifierResult,datingLabels[i])if(classifierResult != datingLabels[i]):errorCount += 1.0print "the total error rate is: %f" % (errorCount / float(numTestVecs))def classifyPerson():percentTats = float(raw_input("输入玩视频游戏所消耗时间的百分比:"))ffMiles = float(raw_input("输入每年获得的飞行常客里程数:"))iceCream = float(raw_input("输入每周消费的冰淇淋公升数:"))datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')normMat,ranges,minVals = autoNorm(datingDataMat)inArr = array([ffMiles,percentTats,iceCream])classifierResult = classify0((inArr-minVals)/ranges, normMat ,datingLabels , 3)print(classifierResult)temp = classifierResult - 1;if temp == 0:print("一点都不喜欢这个人")elif temp == 1:print("一般般")else:print("非常喜欢")def img2vector(filename):returnVect = zeros((1,1024))fr = open(filename)for i in range(32):lineStr = fr.readline()for j in range(32):returnVect[0,32*i+j] = int(lineStr[j])return returnVect #returnVect为1*1024的数组def handwritingClassTest():hwLabels = []trainingFileList = listdir("trainingDigits")m = len(trainingFileList)trainingMat = zeros((m,1024))for i in range(m):  #这是训练集fileNameStr = trainingFileList[i]fileStr = fileNameStr.split('.')[0]classNumStr = int(fileStr.split('_')[0])hwLabels.append(classNumStr)trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)testFileList = listdir('testDigits')errorCount = 0.0mTest = len(testFileList)for i in range(mTest):  #这是测试集fileNameStr = testFileList[i]fileStr = fileNameStr.split('.')[0]classNumStr = int(fileStr.split('_')[0])vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)print "the classifier came back with: %d,the real answer is : %d" % (classifierResult,classNumStr)if(classifierResult != classNumStr) : errorCount += 1.0print "\nthe total number of errors is: %d" % errorCountprint "\nthe total error rate is:%f" % (errorCount / float(mTest))'''
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')
print(datingDataMat)
print(datingLabels[0:20])
normMat,ranges,minVals = autoNorm(datingDataMat)
print('\n')
print(normMat)
print(ranges)
print(minVals)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0 * array(datingLabels))
plt.show()
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.scatter(normMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0 * array(datingLabels))
plt.show()
datingClassTest()
'''
#classifyPerson()
#testVector = img2vector('0_13.txt')
#print testVector[0,0:31]
#print testVector[0,32:63]
handwritingClassTest()


这篇关于机器学习实战(k-近邻算法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1104986

相关文章

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

Redis 配置文件使用建议redis.conf 从入门到实战

《Redis配置文件使用建议redis.conf从入门到实战》Redis配置方式包括配置文件、命令行参数、运行时CONFIG命令,支持动态修改参数及持久化,常用项涉及端口、绑定、内存策略等,版本8... 目录一、Redis.conf 是什么?二、命令行方式传参(适用于测试)三、运行时动态修改配置(不重启服务

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和