转载: scikit-learn学习之K最近邻算法(KNN)
版权声明:<—— 本文为作者呕心沥血打造,若要转载,请注明出处@http://blog.csdn.net/gamer_gyt <——
======================================================================
本系列博客主要参考 Scikit-Learn 官方网站上的每一个算法进行,并进行部分翻译,如有错误,请大家指正
======================================================================
决策树的算法分析与Python代码实现请参考之前的一篇博客:K最近邻Python实现
接下来我主要演示怎么使用Scikit-Learn完成决策树算法的调用
Scikit-Learn中 sklearn.neighbors的函数包括(点击查看来源URL)
The sklearn.neighbors
module
implements the k-nearest neighbors algorithm.
The
sklearn.neighbors
moduleimplements the k-nearest neighbors algorithm.
User guide: See the Nearest Neighbors section
for further details.
neighbors.NearestNeighbors
([n_neighbors, ...])
Classifier implementing the k-nearest neighbors vote.
Classifier implementing a vote among neighbors within a given radius
neighbors.KNeighborsRegressor
([n_neighbors, ...])
neighbors.RadiusNeighborsRegressor
([radius, ...])
neighbors.NearestCentroid
([metric, ...])
BallTree for fast generalized N-point problems
KDTree for fast generalized N-point problems
neighbors.LSHForest
([n_estimators, radius, ...])
DistanceMetric class
neighbors.KernelDensity
([bandwidth, ...])
neighbors.NearestNeighbors
([n_neighbors, ...])
Classifier implementing the k-nearest neighbors vote.
Classifier implementing a vote among neighbors within a given radius
neighbors.KNeighborsRegressor
([n_neighbors, ...])
neighbors.RadiusNeighborsRegressor
([radius, ...])
neighbors.NearestCentroid
([metric, ...])
BallTree for fast generalized N-point problems
KDTree for fast generalized N-point problems
neighbors.LSHForest
([n_estimators, radius, ...])
DistanceMetric class
neighbors.KernelDensity
([bandwidth, ...])
Unsupervised learner for implementing neighbor searches. |
Regression based on k-nearest neighbors. |
Regression based on neighbors within a fixed radius. |
Nearest centroid classifier. |
Performs approximate nearest neighbor search using LSH forest. |
Kernel Density Estimation |
neighbors.kneighbors_graph
(X, n_neighbors[, ...])neighbors.radius_neighbors_graph
(X, radius)
neighbors.kneighbors_graph
(X, n_neighbors[, ...])neighbors.radius_neighbors_graph
(X, radius)
Computes the (weighted) graph of k-Neighbors for points in X |
Computes the (weighted) graph of Neighbors for points in X |
首先看一个简单的小例子:
sklearn.neighbors.NearestNeighbors具体说明查看:URL
在这只是将用到的加以注释
- #coding:utf-8
- '''''
- Created on 2016/4/24
- @author: Gamer Think
- '''
- #导入NearestNeighbor包 和 numpy
- from sklearn.neighbors import NearestNeighbors
- import numpy as np
- #定义一个数组
- X = np.array([[-1,-1],
- [-2,-1],
- [-3,-2],
- [1,1],
- [2,1],
- [3,2]
- ])
- """
- NearestNeighbors用到的参数解释
- n_neighbors=5,默认值为5,表示查询k个最近邻的数目
- algorithm='auto',指定用于计算最近邻的算法,auto表示试图采用最适合的算法计算最近邻
- fit(X)表示用X来训练算法
- """
- nbrs = NearestNeighbors(n_neighbors=3, algorithm="ball_tree").fit(X)
- #返回距离每个点k个最近的点和距离指数,indices可以理解为表示点的下标,distances为距离
- distances, indices = nbrs.kneighbors(X)
- print indices
- print distances
输出结果为:
执行
- #输出的是求解n个最近邻点后的矩阵图,1表示是最近点,0表示不是最近点
- print nbrs.kneighbors_graph(X).toarray()
- #测试 KDTree
- '''''
- leaf_size:切换到蛮力的点数。改变leaf_size不会影响查询结果,
- 但能显著影响查询和存储所需的存储构造树的速度。
- 需要存储树的规模约n_samples / leaf_size内存量。
- 为指定的leaf_size,叶节点是保证满足leaf_size <= n_points < = 2 * leaf_size,
- 除了在的情况下,n_samples < leaf_size。
- metric:用于树的距离度量。默认'minkowski与P = 2(即欧氏度量)。
- 看到一个可用的度量的距离度量类的文档。
- kd_tree.valid_metrics列举这是有效的基础指标。
- '''
- from sklearn.neighbors import KDTree
- import numpy as np
- X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
- kdt = KDTree(X,leaf_size=30,metric="euclidean")
- print kdt.query(X, k=3, return_distance=False)
- #测试 BallTree
- from sklearn.neighbors import BallTree
- import numpy as np
- X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
- bt = BallTree(X,leaf_size=30,metric="euclidean")
- print bt.query(X, k=3, return_distance=False)
其输出结果均为:
这是在小数据集的情况下并不能看到他们的差别,当数据集变大时,这种差别便显而易见了
- <span style="font-size:18px;">#coding:utf-8
- '''''
- Created on 2016年4月24日
- @author: Gamer Think
- '''
- from sklearn.datasets import load_iris
- from sklearn import neighbors
- import sklearn
- #查看iris数据集
- iris = load_iris()
- print iris
- knn = neighbors.KNeighborsClassifier()
- #训练数据集
- knn.fit(iris.data, iris.target)
- #预测
- predict = knn.predict([[0.1,0.2,0.3,0.4]])
- print predict
- print iris.target_names[predict]</span>
预测结果为:
[0] #第0类
['setosa'] #第0类对应花的名字
- <span style="font-size:18px;"> #-*- coding: UTF-8 -*-
- '''''
- Created on 2016/4/24
- @author: Administrator
- '''
- import csv #用于处理csv文件
- import random #用于随机数
- import math
- import operator #
- from sklearn import neighbors
- #加载数据集
- def loadDataset(filename,split,trainingSet=[],testSet = []):
- with open(filename,"rb") as csvfile:
- lines = csv.reader(csvfile)
- dataset = list(lines)
- for x in range(len(dataset)-1):
- for y in range(4):
- dataset[x][y] = float(dataset[x][y])
- if random.random()<split:
- trainingSet.append(dataset[x])
- else:
- testSet.append(dataset[y])
- #计算距离
- def euclideanDistance(instance1,instance2,length):
- distance = 0
- for x in range(length):
- distance = pow((instance1[x] - instance2[x]),2)
- return math.sqrt(distance)
- #返回K个最近邻
- def getNeighbors(trainingSet,testInstance,k):
- distances = []
- length = len(testInstance) -1
- #计算每一个测试实例到训练集实例的距离
- for x in range(len(trainingSet)):
- dist = euclideanDistance(testInstance, trainingSet[x], length)
- distances.append((trainingSet[x],dist))
- #对所有的距离进行排序
- distances.sort(key=operator.itemgetter(1))
- neighbors = []
- #返回k个最近邻
- for x in range(k):
- neighbors.append(distances[x][0])
- return neighbors
- #对k个近邻进行合并,返回value最大的key
- def getResponse(neighbors):
- classVotes = {}
- for x in range(len(neighbors)):
- response = neighbors[x][-1]
- if response in classVotes:
- classVotes[response]+=1
- else:
- classVotes[response] = 1
- #排序
- sortedVotes = sorted(classVotes.iteritems(),key = operator.itemgetter(1),reverse =True)
- return sortedVotes[0][0]
- #计算准确率
- def getAccuracy(testSet,predictions):
- correct = 0
- for x in range(len(testSet)):
- if testSet[x][-1] == predictions[x]:
- correct+=1
- return (correct/float(len(testSet))) * 100.0
- def main():
- trainingSet = [] #训练数据集
- testSet = [] #测试数据集
- split = 0.67 #分割的比例
- loadDataset(r"iris.txt", split, trainingSet, testSet)
- print "Train set :" + repr(len(trainingSet))
- print "Test set :" + repr(len(testSet))
- predictions = []
- k = 3
- for x in range(len(testSet)):
- neighbors = getNeighbors(trainingSet, testSet[x], k)
- result = getResponse(neighbors)
- predictions.append(result)
- print ">predicted = " + repr(result) + ",actual = " + repr(testSet[x][-1])
- accuracy = getAccuracy(testSet, predictions)
- print "Accuracy:" + repr(accuracy) + "%"
- if __name__ =="__main__":
- main() </span>
附iris.txt文件的内容
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.4,3.7,1.5,0.2,Iris-setosa
4.8,3.4,1.6,0.2,Iris-setosa
4.8,3.0,1.4,0.1,Iris-setosa
4.3,3.0,1.1,0.1,Iris-setosa
5.8,4.0,1.2,0.2,Iris-setosa
5.7,4.4,1.5,0.4,Iris-setosa
5.4,3.9,1.3,0.4,Iris-setosa
5.1,3.5,1.4,0.3,Iris-setosa
5.7,3.8,1.7,0.3,Iris-setosa
5.1,3.8,1.5,0.3,Iris-setosa
5.4,3.4,1.7,0.2,Iris-setosa
5.1,3.7,1.5,0.4,Iris-setosa
4.6,3.6,1.0,0.2,Iris-setosa
5.1,3.3,1.7,0.5,Iris-setosa
4.8,3.4,1.9,0.2,Iris-setosa
5.0,3.0,1.6,0.2,Iris-setosa
5.0,3.4,1.6,0.4,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa
5.2,3.4,1.4,0.2,Iris-setosa
4.7,3.2,1.6,0.2,Iris-setosa
4.8,3.1,1.6,0.2,Iris-setosa
5.4,3.4,1.5,0.4,Iris-setosa
5.2,4.1,1.5,0.1,Iris-setosa
5.5,4.2,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.0,3.2,1.2,0.2,Iris-setosa
5.5,3.5,1.3,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
4.4,3.0,1.3,0.2,Iris-setosa
5.1,3.4,1.5,0.2,Iris-setosa
5.0,3.5,1.3,0.3,Iris-setosa
4.5,2.3,1.3,0.3,Iris-setosa
4.4,3.2,1.3,0.2,Iris-setosa
5.0,3.5,1.6,0.6,Iris-setosa
5.1,3.8,1.9,0.4,Iris-setosa
4.8,3.0,1.4,0.3,Iris-setosa
5.1,3.8,1.6,0.2,Iris-setosa
4.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
5.5,2.3,4.0,1.3,Iris-versicolor
6.5,2.8,4.6,1.5,Iris-versicolor
5.7,2.8,4.5,1.3,Iris-versicolor
6.3,3.3,4.7,1.6,Iris-versicolor
4.9,2.4,3.3,1.0,Iris-versicolor
6.6,2.9,4.6,1.3,Iris-versicolor
5.2,2.7,3.9,1.4,Iris-versicolor
5.0,2.0,3.5,1.0,Iris-versicolor
5.9,3.0,4.2,1.5,Iris-versicolor
6.0,2.2,4.0,1.0,Iris-versicolor
6.1,2.9,4.7,1.4,Iris-versicolor
5.6,2.9,3.6,1.3,Iris-versicolor
6.7,3.1,4.4,1.4,Iris-versicolor
5.6,3.0,4.5,1.5,Iris-versicolor
5.8,2.7,4.1,1.0,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
5.6,2.5,3.9,1.1,Iris-versicolor
5.9,3.2,4.8,1.8,Iris-versicolor
6.1,2.8,4.0,1.3,Iris-versicolor
6.3,2.5,4.9,1.5,Iris-versicolor
6.1,2.8,4.7,1.2,Iris-versicolor
6.4,2.9,4.3,1.3,Iris-versicolor
6.6,3.0,4.4,1.4,Iris-versicolor
6.8,2.8,4.8,1.4,Iris-versicolor
6.7,3.0,5.0,1.7,Iris-versicolor
6.0,2.9,4.5,1.5,Iris-versicolor
5.7,2.6,3.5,1.0,Iris-versicolor
5.5,2.4,3.8,1.1,Iris-versicolor
5.5,2.4,3.7,1.0,Iris-versicolor
5.8,2.7,3.9,1.2,Iris-versicolor
6.0,2.7,5.1,1.6,Iris-versicolor
5.4,3.0,4.5,1.5,Iris-versicolor
6.0,3.4,4.5,1.6,Iris-versicolor
6.7,3.1,4.7,1.5,Iris-versicolor
6.3,2.3,4.4,1.3,Iris-versicolor?
5.6,3.0,4.1,1.3,Iris-versicolor
5.5,2.5,4.0,1.3,Iris-versicolor
5.5,2.6,4.4,1.2,Iris-versicolor
6.1,3.0,4.6,1.4,Iris-versicolor
5.8,2.6,4.0,1.2,Iris-versicolor
5.0,2.3,3.3,1.0,Iris-versicolor
5.6,2.7,4.2,1.3,Iris-versicolor
5.7,3.0,4.2,1.2,Iris-versicolor
5.7,2.9,4.2,1.3,Iris-versicolor
6.2,2.9,4.3,1.3,Iris-versicolor
5.1,2.5,3.0,1.1,Iris-versicolor
5.7,2.8,4.1,1.3,Iris-versicolor
6.3,3.3,6.0,2.5,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
7.1,3.0,5.9,2.1,Iris-virginica
6.3,2.9,5.6,1.8,Iris-virginica
6.5,3.0,5.8,2.2,Iris-virginica
7.6,3.0,6.6,2.1,Iris-virginica
4.9,2.5,4.5,1.7,Iris-virginica
7.3,2.9,6.3,1.8,Iris-virginica
6.7,2.5,5.8,1.8,Iris-virginica
7.2,3.6,6.1,2.5,Iris-virginica
6.5,3.2,5.1,2.0,Iris-virginica
6.4,2.7,5.3,1.9,Iris-virginica
6.8,3.0,5.5,2.1,Iris-virginica
5.7,2.5,5.0,2.0,Iris-virginica
5.8,2.8,5.1,2.4,Iris-virginica
6.4,3.2,5.3,2.3,Iris-virginica
6.5,3.0,5.5,1.8,Iris-virginica
7.7,3.8,6.7,2.2,Iris-virginica
7.7,2.6,6.9,2.3,Iris-virginica
6.0,2.2,5.0,1.5,Iris-virginica
6.9,3.2,5.7,2.3,Iris-virginica
5.6,2.8,4.9,2.0,Iris-virginica
7.7,2.8,6.7,2.0,Iris-virginica
6.3,2.7,4.9,1.8,Iris-virginica
6.7,3.3,5.7,2.1,Iris-virginica
7.2,3.2,6.0,1.8,Iris-virginica
6.2,2.8,4.8,1.8,Iris-virginica
6.1,3.0,4.9,1.8,Iris-virginica
6.4,2.8,5.6,2.1,Iris-virginica
7.2,3.0,5.8,1.6,Iris-virginica
7.4,2.8,6.1,1.9,Iris-virginica
7.9,3.8,6.4,2.0,Iris-virginica
转载: scikit-learn学习之K最近邻算法(KNN)的更多相关文章
- k最近邻算法(kNN)
from numpy import * import operator from os import listdir def classify0(inX, dataSet, labels, k): d ...
- 图说十大数据挖掘算法(一)K最近邻算法
如果你之前没有学习过K最近邻算法,那今天几张图,让你明白什么是K最近邻算法. 先来一张图,请分辨它是什么水果 很多同学不假思索,直接回答:“菠萝”!!! 仔细看看同学们,这是菠萝么?那再看下边这这张图 ...
- 机器学习【一】K最近邻算法
K最近邻算法 KNN 基本原理 离哪个类近,就属于该类 [例如:与下方新元素距离最近的三个点中,2个深色,所以新元素分类为深色] K的含义就是最近邻的个数.在sklearn中,KNN的K值是通过n ...
- PCB 加投率计算实现基本原理--K最近邻算法(KNN)
PCB行业中,客户订购5000pcs,在投料时不会直接投5000pcs,因为实际在生产过程不可避免的造成PCB报废, 所以在生产前需计划多投一定比例的板板, 例:订单 量是5000pcs,加投3%,那 ...
- 【算法】K最近邻算法(K-NEAREST NEIGHBOURS,KNN)
K最近邻算法(k-nearest neighbours,KNN) 算法 对一个元素进行分类 查看它k个最近的邻居 在这些邻居中,哪个种类多,这个元素有更大概率是这个种类 使用 使用KNN来做两项基本工 ...
- 《算法图解》——第十章 K最近邻算法
第十章 K最近邻算法 1 K最近邻(k-nearest neighbours,KNN)——水果分类 2 创建推荐系统 利用相似的用户相距较近,但如何确定两位用户的相似程度呢? ①特征抽取 对水果 ...
- 12、K最近邻算法(KNN算法)
一.如何创建推荐系统? 找到与用户相似的其他用户,然后把其他用户喜欢的东西推荐给用户.这就是K最近邻算法的分类作用. 二.抽取特征 推荐系统最重要的工作是:将用户的特征抽取出来并转化为度量的数字,然后 ...
- [笔记]《算法图解》第十章 K最近邻算法
K最近邻算法 简称KNN,计算与周边邻居的距离的算法,用于创建分类系统.机器学习等. 算法思路:首先特征化(量化) 然后在象限中选取目标点,然后通过目标点与其n个邻居的比较,得出目标的特征. 余弦相似 ...
- K最近邻算法项目实战
这里我们用酒的分类来进行实战练习 下面来代码 1.把酒的数据集载入到项目中 from sklearn.datasets import load_wine #从sklearn的datasets模块载入数 ...
随机推荐
- 程序员是怎么炼成的---OC题集--练习答案与题目(2)
1.objective-c中有垃圾回收机制吗? 没有像java.C#一样的垃圾回收机制,但是有ARC自动引用计数器技术,根据对象的引用技术来判断对象是否还在使用,如果RC=0,则系统就会销毁对象,实 ...
- 3、C#基础整理(语句概述)
语句 语句分为四个大类: * 分支语句:if,if... else,if ...else if... else,switch case * 循环语句:for,while,do while,foreac ...
- 17、SQL基础整理(事务)
事务 事务==流程控制 确保流程只能成功或者失败,若出现错误会自动回到原点 例: begin tran insert into student values('111','王五','男','1999- ...
- PHP访问REST API上传文件的解决方案
最近写的一个小功能需要通过rest方式上传文件,因此就在网上找了一些解决方案.接下来说明以下我采用的解决方案:我是利用curl来实现的,其中CURLOPT_POST的值为TRUE代表的是请求类型为PO ...
- mysql联合索引详解
联合索引又叫复合索引.对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索 引中的一部份,但只能是最左侧部分.例如索引是key index (a,b,c). 可以支持a | a,b ...
- Unity3d Shader
Unity3d Shader 预览Surface Shader主要用来实现光照相关处理,可能更简洁. Vertex and Fragment Shader 如果不与光照交互, 则可以用这个shader ...
- 【题解】【链表】【Leetcode】Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 九 EJB
一 EJB 1. 定义:EJB 就是一组用 Java 语言编写的包含字段和方法的代码体,而这些代码的核心任务就是实现纯粹的业务逻辑. 2. EJB 和 JavaBean 的相同点: a) 都有 get ...
- 检测到在集成的托管管道模式下不适用的 ASP.NET 设置的解决方法
在将应用程序从经典模式迁移到集成模式时,可以保留经典模式下的自定义模块和处理程序注册,也可以将这些注册移除.如果不移除经典模式下使用的 httpModules 和 httpHandlers 注册,则必 ...
- Android滑动选择的日期选择框
效果图如下. 实现也很简单,使用的是Android的DatePicker控件.AlertDialog实现. 首先是布局文件:date_picker_dialog.xml <?xml versio ...