本文是针对《机器学习实战》(第二章)内所需要的程序代码进行修改(书中使用的是py2),现已py3呈现。
本文中不同之处可以通过《机器学习实战》中函数详细解析(持续更新)这篇文章进行寻找,并且也可以根据页数进行函数的查看用法等。
程序清单2-1:
from numpy import *
import operator
def createDataSet():
"""
funct:建立数据集和特征值
:return:
group:建立好的数据集
labels:建立好的特征值
"""
#建立数据集
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
#建立特征值
labels = ['A','A','B','B']
return group,labels
def classify(inX,dataSet,labels,k):
"""
funct:使用k-邻近算法将每组数据划分到某个类中
:param inX:
:param dataSet:训练样本集
:param labels:标签向量
:param k:用于选择最近邻居的数量
:return:
"""
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]
group,labels = createDataSet()
print(classify([0,0],group,labels,k=3))
#运行结果:B
程序清单2-2:
from numpy import *
import operator
from numpy.ma import zeros, array
import matplotlib
import matplotlib.pyplot as plt
def file2matrix(fileName):
#数据格式如下
# 40920 8.326976 0.953952 3
# 14488 7.153469 1.673904 2
file = open(fileName)
#读取行数
arrayOLines = file.readlines()
numberOfLines = len(arrayOLines)
returnMatrix = ma.zeros((numberOfLines,3))
classLabelVector = []
index = 0
for line in arrayOLines:
line = line.strip()
listFromLine = line.split('\t')
returnMatrix[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMatrix,classLabelVector
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter((datingDataMat[:,1]).tolist(),(datingDataMat[:,2]).tolist())
plt.show()
运行结果:
程序难点:在书上内部的代码是直接将datingDataMat[:,1]直接传给了ax.scatter()但是会报错,查看报错信息,发现由于版本的差异我们只能传入list,所以我们使用了array.tolist()函数。
修改代码ax.scatter((datingDataMat[:,1]).tolist(),(datingDataMat[:,2]).tolist(),15.0*array(datingLabels)
,15.0*array(datingLabels))生成的图像如下:
程序清单2-3:
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))
#normDataSet = linalg.solve(normDataSet,tile(range,(m,1)))
return normDataSet,range,minVals
编码时犯的错:pycharm补齐的时候,不小心漏掉了ranges里面的s,浪费了很多时间。
程序清单2-4:
def classifyPerson():
resultList = ['not at all','in small doses','in large doses']
percentTats = float(input("1"))
ffMiles = float(input("2"))
iceCream = float(input("3"))
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')
normMat,ranges1,minVals = autoNorm(datingDataMat)
inArr = array([ffMiles,percentTats,iceCream])
classifierResult = classify((inArr - minVals)/ranges1,normMat,datingLabels,3)
print("you will probably like the person:",resultList[classifierResult-1])
程序清单2-5:
def img2vector(fileName):
returnVect = zeros((1,1024))
file = open(fileName)
for i in range(32):
lineStr = file.readline()
for j in range(32):
returnVect[0,32*i+j] = int(lineStr[j])
return returnVect
def handWritingClassTest():
hwLabels = []
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector('trainingDigits/%s'%fileNameStr)
testFileList = listdir('testDigits')
errorCount = 0.0
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
vectorUnderTest = img2vector('testDigits/%s'%fileNameStr)
classifierResult = classify(vectorUnderTest,trainingMat,hwLabels,3)
print("the classifier is:%d,real answer is:%d"%(classifierResult,classNumStr))
if(classifierResult != classNumStr):errorCount+=1.0
print("\nthe total number of error is:%d"%errorCount)
print("\nthe total error rate id:%f"%(errorCount/float(mTest)))