转载: 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.

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, ...])

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)

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 
在这只是将用到的加以注释

  1. #coding:utf-8
  2. '''''
  3. Created on 2016/4/24
  4. @author: Gamer Think
  5. '''
  6. #导入NearestNeighbor包 和 numpy
  7. from sklearn.neighbors import NearestNeighbors
  8. import numpy as np
  9. #定义一个数组
  10. X = np.array([[-1,-1],
  11. [-2,-1],
  12. [-3,-2],
  13. [1,1],
  14. [2,1],
  15. [3,2]
  16. ])
  17. """
  18. NearestNeighbors用到的参数解释
  19. n_neighbors=5,默认值为5,表示查询k个最近邻的数目
  20. algorithm='auto',指定用于计算最近邻的算法,auto表示试图采用最适合的算法计算最近邻
  21. fit(X)表示用X来训练算法
  22. """
  23. nbrs = NearestNeighbors(n_neighbors=3, algorithm="ball_tree").fit(X)
  24. #返回距离每个点k个最近的点和距离指数,indices可以理解为表示点的下标,distances为距离
  25. distances, indices = nbrs.kneighbors(X)
  26. print indices
  27. print distances

输出结果为:

转载: scikit-learn学习之K最近邻算法(KNN)
执行

  1. #输出的是求解n个最近邻点后的矩阵图,1表示是最近点,0表示不是最近点
  2. print nbrs.kneighbors_graph(X).toarray()

转载: scikit-learn学习之K最近邻算法(KNN)

  1. #测试 KDTree
  2. '''''
  3. leaf_size:切换到蛮力的点数。改变leaf_size不会影响查询结果,
  4. 但能显著影响查询和存储所需的存储构造树的速度。
  5. 需要存储树的规模约n_samples / leaf_size内存量。
  6. 为指定的leaf_size,叶节点是保证满足leaf_size <= n_points < = 2 * leaf_size,
  7. 除了在的情况下,n_samples < leaf_size。
  8. metric:用于树的距离度量。默认'minkowski与P = 2(即欧氏度量)。
  9. 看到一个可用的度量的距离度量类的文档。
  10. kd_tree.valid_metrics列举这是有效的基础指标。
  11. '''
  12. from sklearn.neighbors import KDTree
  13. import numpy as np
  14. X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
  15. kdt = KDTree(X,leaf_size=30,metric="euclidean")
  16. print kdt.query(X, k=3, return_distance=False)
  17. #测试 BallTree
  18. from sklearn.neighbors import BallTree
  19. import numpy as np
  20. X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
  21. bt = BallTree(X,leaf_size=30,metric="euclidean")
  22. print bt.query(X, k=3, return_distance=False)

其输出结果均为:

转载: scikit-learn学习之K最近邻算法(KNN)

这是在小数据集的情况下并不能看到他们的差别,当数据集变大时,这种差别便显而易见了

转载: scikit-learn学习之K最近邻算法(KNN)转载: scikit-learn学习之K最近邻算法(KNN)

  1. <span style="font-size:18px;">#coding:utf-8
  2. '''''
  3. Created on 2016年4月24日
  4. @author: Gamer Think
  5. '''
  6. from sklearn.datasets import load_iris
  7. from sklearn import neighbors
  8. import sklearn
  9. #查看iris数据集
  10. iris = load_iris()
  11. print iris
  12. knn = neighbors.KNeighborsClassifier()
  13. #训练数据集
  14. knn.fit(iris.data, iris.target)
  15. #预测
  16. predict = knn.predict([[0.1,0.2,0.3,0.4]])
  17. print predict
  18. print iris.target_names[predict]</span>

预测结果为:

[0]    #第0类
['setosa']    #第0类对应花的名字

转载: scikit-learn学习之K最近邻算法(KNN)转载: scikit-learn学习之K最近邻算法(KNN)

  1. <span style="font-size:18px;"> #-*- coding: UTF-8 -*-
  2. '''''
  3. Created on 2016/4/24
  4. @author: Administrator
  5. '''
  6. import csv     #用于处理csv文件
  7. import random    #用于随机数
  8. import math
  9. import operator  #
  10. from sklearn import neighbors
  11. #加载数据集
  12. def loadDataset(filename,split,trainingSet=[],testSet = []):
  13. with open(filename,"rb") as csvfile:
  14. lines = csv.reader(csvfile)
  15. dataset = list(lines)
  16. for x in range(len(dataset)-1):
  17. for y in range(4):
  18. dataset[x][y] = float(dataset[x][y])
  19. if random.random()<split:
  20. trainingSet.append(dataset[x])
  21. else:
  22. testSet.append(dataset[y])
  23. #计算距离
  24. def euclideanDistance(instance1,instance2,length):
  25. distance = 0
  26. for x in range(length):
  27. distance = pow((instance1[x] - instance2[x]),2)
  28. return math.sqrt(distance)
  29. #返回K个最近邻
  30. def getNeighbors(trainingSet,testInstance,k):
  31. distances = []
  32. length = len(testInstance) -1
  33. #计算每一个测试实例到训练集实例的距离
  34. for x in range(len(trainingSet)):
  35. dist = euclideanDistance(testInstance, trainingSet[x], length)
  36. distances.append((trainingSet[x],dist))
  37. #对所有的距离进行排序
  38. distances.sort(key=operator.itemgetter(1))
  39. neighbors = []
  40. #返回k个最近邻
  41. for x in range(k):
  42. neighbors.append(distances[x][0])
  43. return neighbors
  44. #对k个近邻进行合并,返回value最大的key
  45. def getResponse(neighbors):
  46. classVotes = {}
  47. for x in range(len(neighbors)):
  48. response = neighbors[x][-1]
  49. if response in classVotes:
  50. classVotes[response]+=1
  51. else:
  52. classVotes[response] = 1
  53. #排序
  54. sortedVotes = sorted(classVotes.iteritems(),key = operator.itemgetter(1),reverse =True)
  55. return sortedVotes[0][0]
  56. #计算准确率
  57. def getAccuracy(testSet,predictions):
  58. correct = 0
  59. for x in range(len(testSet)):
  60. if testSet[x][-1] == predictions[x]:
  61. correct+=1
  62. return (correct/float(len(testSet))) * 100.0
  63. def main():
  64. trainingSet = []  #训练数据集
  65. testSet = []      #测试数据集
  66. split = 0.67      #分割的比例
  67. loadDataset(r"iris.txt", split, trainingSet, testSet)
  68. print "Train set :" + repr(len(trainingSet))
  69. print "Test set :" + repr(len(testSet))
  70. predictions = []
  71. k = 3
  72. for x in range(len(testSet)):
  73. neighbors = getNeighbors(trainingSet, testSet[x], k)
  74. result = getResponse(neighbors)
  75. predictions.append(result)
  76. print ">predicted = " + repr(result) + ",actual = " + repr(testSet[x][-1])
  77. accuracy = getAccuracy(testSet, predictions)
  78. print "Accuracy:" + repr(accuracy) + "%"
  79. if __name__ =="__main__":
  80. 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

上一篇:阿里云最新活动导航栏改版了:限量神券 必抢爆款 精选活动助力用户优惠上云


下一篇:Centos7下修改mysql5.6编码方式 解决网站中文显示问号