读书笔记:机器学习实战(1)——章2的knn代码和个人改进与注释

最近在学习《机器学习实战》一书,受益匪浅,之前还看过本书《机器学习系统设计》也很不错,个人觉得前者更注重算法学习和白盒代码优化(原理理解),而后者更注重skit-learn 等工具包的黑盒使用,更重要的是会指导部分工具算法使用的调优trick,提到机器学习的trick调优,比如early-stoping等,《Neural networks and deep learning》中讲授了很多精华,但是目前我只有电子版,同时鉴于英文功底,暂时还没详读。
言归正传,这是我学习《Machine Learning in Action》,对于第二章inn代码的个人理解,python代码学习备注,和一些小的调优尝试

#!/usr/bin/env python
# coding=utf-8
__author__ = 'zhangdebin'
from numpy import *
import operator
from os import listdir
import time

def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize,1)) - dataSet
    # 以测试数据为基础,构造一个 dataSetSize*1的矩阵,和所有测试数据的矩阵进行求差(曼哈顿距离,L1)
    sqDiffMat = diffMat**2
    # sqDistances = sqDiffMat.sum(axis=1)
    sqDistances = transpose(sqDiffMat)[:,0]
    # 原书代码为按行求和,axis=0为按列,这里觉得也可以转置矩阵,因为每行只有1列,
    # 但是转置后是一个[[1,2,3]]的“多列”矩阵,需要提取数组的第一列
    # 测试证明这样操作计算更快,耗时由0.047降低为0.023
    distances = sqDistances**0.5
    # L2,欧式距离
    sortedDistIndicies = distances.argsort() #返回distances数组从小到大的索引
    classCount={}          
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    #reverse=True 从小到大排序,默认为从大到小(False) key和cmp两种比较方式,但是key更快,详见印象笔记(sort and sorted)
    return sortedClassCount[0][0]

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 file2matrix(filename):
    fr = open(filename)
    numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = zeros((numberOfLines,3))        #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 returnMat,classLabelVector

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

def datingClassTest():
    hoRatio = 0.50      #hold out 10%测试集百分比
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):
        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)
        # k逐渐增大,准确率会有一定增长,因为是矩阵对所有做差,求和(L2),所以k增加,计算耗时增加很少,本机测ms级
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])
        if (classifierResult != datingLabels[i]): errorCount += 1.0
    print "the total error rate is: %f" % (errorCount/float(numTestVecs))
    print errorCount

def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('trainingDigits')           #load the training set
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
    testFileList = listdir('testDigits')        #iterate through the test set
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)
        if (classifierResult != classNumStr): errorCount += 1.0
    print "\nthe total number of errors is: %d" % errorCount
    print "\nthe total error rate is: %f" % (errorCount/float(mTest))

if  __name__ == '__main__':
    time1=time.time()
    datingClassTest()
    time2=time.time()
    print "耗时:"
    print (time2-time1)

其他学习笔记会陆续补充,还有一些工作时候的个人实践

你可能感兴趣的:(机器学习,算法温习,python学习,代码,优化,机器学习,python,读书笔记)