在看完机器学习实战第一章及敲完代码的总结

来源:互联网 发布:网络电视怎么打开 编辑:程序博客网 时间:2024/06/13 02:40

仅供参考,欢迎指正。
第一:
k近邻算法的核心:训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一数据与所属分类的对应关系。输人没有标签的新数据后,将新数据的每个特征与样本集中数据对应的 特征进行比较,然后算法提取样本集中特征最相似数据(最近邻)的分类标签。
第二:
示例:使用K近邻算法改进约会网站的配对效果
第一个 classify0 函数(该算法的核心)起到分类的作用;首先看有几行,然后用tile函数(个人感觉这里很关键,第一个是模型,然后时行数,重复次数),然后就是算他们之间的距离,从小到大排序后提取他们的原来的所用到sortedDistIndicies中。接下来的一个循环时选出前k项,然后这k项有重复的。在进行计数后,再生成新的字典。再排序。reverse默认升序operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。取得第一维度的值。

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):        votellabel=labels[sortedDistIndicies[i]]        classCount[votellabel]=classCount.get(votellabel,0)    sortedClassCount = sorted(classCount.items(),key = operator.itemgetter(1),reverse = True)    return sortedClassCount[0][0]

第二个重要的函数 file2matrix 。它是将文件中的文本,转换为矩阵。

def file2matrix(filename):    fr=open(filename)    arrayOLines=fr.readlines()    numberOfLines=len(arrayOLines)    returnMat=zeros((numberOfLines,3))    classLabelVector=[]    index=0    for line in arrayOLines:        line = line.strip('\n')        listFromLine = line.split('\t')        returnMat[index,:]=listFromLine[0:3]        classLabelVector.append((int)(listFromLine[-1]))        index +=1    return returnMat,classLabelVector

第三个重要的就是 autoNorm 函数。它避免了三个特征值影响差距较大,因为,其中一项的数值较大,所以要归一化。

def autoNorm(dataSet):    minVals=dataSet.min(0)    maxVals=dataSet.max(0)    ranges=minVals-maxVals    normDataSet=zeros(shape(dataSet))    m=dataSet.shape[0]    normDataSet=dataSet-tile(minVals,(m,1))    normDataSet=normDataSet/tile(ranges,(m,1))    return normDataSet,ranges,minVals

其他函数是建立在三个函数上,在此不说了。还有一个书写数字识别时文本格式,个人认为不太符合常规,且已用神经网络实现,在此就不说了。