机器学习实战2-运行KNN示例

来源:互联网 发布:南京天梯培训中心 知乎 编辑:程序博客网 时间:2024/06/06 08:37

环境配置

代码存放地方为:
C:\PyCode\ML\knn\Ch02

查看当前Python版本
查看Python版本

切换Anaconda的编译环境,激活Python2

查看当前Python编译环境

进入Python编译环境

导入数据

导入knn模块(也就是knn.py文件),导入数据

使用Matplotlib画图

导入matplotlib包时显示不存在,quit()退出当前Python环境,在anaconda中安装matplotlib包,conda install matplotlib

使用第二个和第三个特征画散点图
这里写图片描述

这里写图片描述

使用不同大小颜色的点区分不同类别的数据

>>> import matplotlib.pyplot as plt>>> import numpy as np>>> fig = plt.figure()>>> ax = fig.add_subplot(111)>>> ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels))#以第二列和第三列为x,y轴画出散列点,给予不同的大小和颜色,第一个15.0*np.array(datingLabels)表示散列点的大小,第二个15.0*np.array(datingLabels)表示散列点的颜色#scatter(x,y,s=1,c="g",marker="s",linewidths=0)  #s:散列点的大小,c:散列点的颜色,marker:形状,linewidths:边框宽度  >>> plt.xlabel('Percentage of time spent on playing games')>>> plt.ylabel('Ice cream consumed per week'>>> plt.show()

运行结果为:
这里写图片描述

测试knn分类器的准确性

这里写图片描述
这里写图片描述

实际预测函数

>>> def datingClassTest():...     ratio = 0.1...     datingDataMat, datingLabels = knn.file2matrix('datingTestSet.txt')...     normMat, ranges, minVals = autoNorm(datingDataMat)...     m = normMat.shape[0]...     numTestVecs = int(m*ratio)...     errorCount = 0.0...     for i in range(numTestVects):...         classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)...         print "the classifier came back with:%d,the real is: %d" % (classifierResult, datingLabels[i])...         if(classifierResult != datingLabels[i]): errorCount += 1.0...     print "the total error rate is %f" %(errorCount/float(numTestVecs))

这里写图片描述

原创粉丝点击