第一次用Python,第一次编写机器学习的程序。所做完全是照葫芦画瓢。光是写入代码并运行就花了好久好久,真的是还有好远的路要走啊。
先附上代码吧。我是用sublime Text写的。编译环境是Python 3.63
from numpy import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
def classify0(inX, dataSet, labels , k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,(dataSetSize,1)) - 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(voteIlabel,0)+1
sortedClassCount = sorted(classCount.items(),
key=operator.itemgetter(1), reverse = True)
return sortedClassCount[0][0]
import kNN
group1,labels1 =kNN.createDataSet()
kNN.classify0([0,0],group1,labels1,3<