资源简介
用Python3.5实现的KNN算法,Python2只要去掉print的括号就可以正常使用
代码片段和文件信息
# -*- coding: utf-8 -*-
“““
Spyder Editor
This is a temporary script file.
“““
‘‘‘
Created on Sep 16 2010
kNN: k Nearest Neighbors
Input: inX: vector to compare to existing dataset (1xN)
dataSet: size m data set of known vectors (NxM)
labels: data set labels (1xM vector)
k: number of neighbors to use for comparison (should be an odd number)
Output: the most popular class label
@author: pbharrin
‘‘‘
import numpy
import operator
def createDataSet():
group = numpy.array([[1.01.1][1.01.0][00][00.1]])
labels = [‘A‘‘A‘‘B‘‘B‘]
return group labels
def classify0(inX dataSet labels k):
dataSetSize = dataSet.shape[0]
diffMat = numpy.tile(inX (dataSetSize1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel0) + 1
return sortedClassCount[0][0]
if __name__== “__main__“:
# 导入数据
dataset labels = createDataSet()
inX = [0.1 0.1]
# 简单分类
className = classify0(inX dataset labels 3)
print (‘the class of test sample is %s‘ %className)
#def file2matrix(filename):
# fr = open(filename)
# numberOfLines = len(fr.readlines()) #get the number of lines in the file
# returnMat = numpy.zeros((numberOfLines3)) #prepare matrix to return
# classLabelVector = [] #prepare labels return
# fr = open(filename)
# index = 0
# for line in fr.readlines():
# line = line.strip()
# listFromLine = line.split(‘\t‘)
# returnMat[index:] = listFromLine[0:3]
# classLabelVector.append(int(listFromLine[-1]))
# index += 1
# return returnMatclassLabelVector
#
#def autoNorm(dataSet):
# minVals = dataSet.min(0)
# maxVals = dataSet.max(0)
# ranges = maxVals - minVals
# normDataSet = numpy.zeros(listdir.shape(dataSet))
# m = dataSet.shape[0]
# normDataSet = dataSet - listdir.tile(minVals (m1))
# normDataSet = normDataSet/listdir.tile(ranges (m1)) #element
- 上一篇:python聊天室
- 下一篇:python 获取 去哪儿网 火车票信息
评论
共有 条评论