机器学习笔记1-k近邻算法的实现(1)
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
plt.xlabel(‘Percentage of Time Spent Playing Video Games’)
plt.ylabel(‘Liters of Ice Cream Consumed Per Week’)
plt.show()
3D图:
import numpy
import kNN
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection=‘3d’)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax.set_xlabel(‘mei nian huo qu de fei xing chang ke li cheng shu’)
ax.set_ylabel(‘wan you xi shi jian bi li’)
ax.set_zlabel(‘mei zhou xiao hao de bing qi li shuliang’)
plt.show()
多图:
import numpy
import kNN
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(311)
datingDataMat,datingLabels = kNN.file2matrix(‘f:\\datingTestSet.txt’)
ax1.scatter(datingDataMat[:,0],datingDataMat[:,1],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax1.set_xlabel(‘fly’)
ax2 = fig.add_subplot(312)
ax2.scatter(datingDataMat[:,0],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
ax2 = fig.add_subplot(313)
ax2.scatter(datingDataMat[:,1],datingDataMat[:,2],
15.0*numpy.array(datingLabels),15.0*numpy.array(datingLabels))
plt.show()
不熟悉的函数:
add_subplot:用于指定图像的位置,例如111,指图像分成一行一列,在第一幅图上画
scatter:画散点图,必须输入的有x,y坐标,可选项有颜色形状等
zero:创建0矩阵
归一化:
处理不同取值范围的特征值时,通常需要将数值未硬化,如果将取值范围处理为0到1或者-1到1之间,下面公式可以将任意取值范围的特征值转化为0到1的区间内
newValue = (oldValue-min)/(max-min)
min,max分别是数据集中特征值最大值和最小值,程序如下
def autoNum(dataSet):
#获取每一列的最小值
minVals = dataSet.min(0)
#获取每一列的最大值
maxVals = dataSet.max(0)
#最大值和最小值的差
ranges = maxVals - minVals
#将每一行归一化
normDataSet = numpy.zeros(numpy.shape(dataSet))
m = dataSet.shape[0]
normDataSet = dataSet - numpy.tile(minVals,(m,1))
normDataSet = normDataSet/numpy.tile(ranges,(m,1))
return normDataSet,ranges,minVals
容易搞错的是min(0)返回的是每一列的最小值,而不是第0列的最小值,min()返回的是所有值的最小值,min(1)返回的是每一行的最小值
测试程序:
def datingClassTest():
‘’’
用于测试分类器
‘’’
hoRatio = 0.10
datingDataMating,datingLabels = file2matrix(‘f:\\datingTestSet.txt’)
normMat,ranges,minVals = autoNum(datingDataMating)
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)
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)))
测试结果:
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:3
the classifier came back with: 1,the real answer is:1
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:3
the classifier came back with: 3,the real answer is:3
the classifier came back with: 2,the real answer is:2
the classifier came back with: 1,the real answer is:1
the classifier came back with: 3,the real answer is:1
the total error rate is:0.050000
完整的程序(python3可运行):
import numpy
import operator
def createDataSet():
‘’’
返回一个训练集和标签向量
‘’’
#训练集
group = numpy.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):
‘’’
用于实现k_近邻算法,接收输入一个向量,一个训练集,一个标签向量,一个K值
判断向量所属的类别
‘’’
#读取矩阵第一维度的长度
dataSetSize = dataSet.shape[0]
#输入向量与训练集差值的数组
diffMat = numpy.tile(inX,(dataSetSize,1)) - dataSet
#计算各点与训练集的距离
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distance = sqDistances**0.5
#将距离数组的下标按照距离大小排序
sortedDistIndicies = distance.argsort()
classCount = {}
#在k的范围内,分别计算两类的数目
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
#以k以内类别数目排序
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),
reverse = True)
#返回数目最多的类(即输入向量应该属于的类)
return sortedClassCount[0][0]
def file2matrix(filename):
‘’’
用于解析训练集文件
‘’’
ValueOfClassLabel = {}
Value = [1,2,3]
def getValueOfClassLabel(ClassLabel):
val = 1;
if not ClassLabel in ValueOfClassLabel.keys():
ValueOfClassLabel[ClassLabel] = Value.pop()
return ValueOfClassLabel[ClassLabel]
file = open(filename)
arrayOLines = file.readlines()
#文件的行数
numberOfLines = len(arrayOLines)
如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费学习大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。
一、Python所有方向的学习路线
Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件
工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、全套PDF电子书
书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。

四、入门学习视频
我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。


四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

五、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
更多推荐
所有评论(0)