机器学习实战笔记之二(k-近邻算法)

来源:互联网 发布:ember.js angularjs 编辑:程序博客网 时间:2024/05/17 05:58


优点:精度高、对异常值不敏感、无数据输入假定。

缺点:计算复杂度高、空间复杂度高。

适用数据范围:数值型和标称型。


一般流程:

  1. 收集数据:可以使用任何方法。
  2. 准备数据:距离计算所需要的数值,最好是结构化的数据格式。
  3. 分析数据:可以使用任何方法。
  4. 训练算法:此步骤不适用于k-近邻算法。
  5. 测试算法:计算错误率。
  6. 使用算法:首先需要输入样本数据和结构化的输出结果,然后运行k-近邻算法判定输入数据分别属于哪个分类,最后应用对计算出的分类执行后续的处理。

chapter 2.1.2 从文本文件中解析数据

#! usr/bin/python#coding=utf-8# -*- coding:cp936 -*-from numpy import *import operatordef createDataSet():    group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])    labels=['A','A','B','B']    return group, labels# inX 用于分类的输入向量# dataSet 输入的训练样本集# labels 标签向量# k 用于选择最近邻居的数目def classify0(inX,dataSet,labels,k):    # 计算两个向量点xA和xB之间的距离(欧氏距离公式)    dataSetSize=dataSet.shape[0] # shape[0]计算行,shape[1]计算列    diffMat=tile(inX,(dataSetSize,1))-dataSet    sqDiffMat=diffMat**2    sqDistances=sqDiffMat.sum(axis=1)    distances=sqDistances**0.5    sortedDistIndicies=distances.argsort() # 返回的是数组值从小到大的索引值    classCount={}    # 选择距离最小的k个点    for i in range(k):        voteIlabel=labels[sortedDistIndicies[i]]        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1 # dict.get(key,default=None) 返回一个给定的key对应的值。如果key是没有用的,然后返回默认值None返回。    # 排序    sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)    return sortedClassCount[0][0]


 如何测试分类器:错误率是常用的评估方法,主要用于评估分类器在某个数据集上的执行效果。

完美分类器的错误率为0,最差分类器的错误率是1.0。


==================我是matplotlib分割线==================

chapter 2.2.2 分析数据:使用 Matplotlib 创建散点图

matplotlib.pyplot

matplotlib的pyplot子库提供了和matlab类似的绘图API,方便用户快速绘制2D图表。
matplotlib.pyplot是命令行式函数的集合,每一个函数都对图像作了修改,比如创建图形,在图像上创建画图区域,在画图区域上画线,在线上标注等。

转自 http://blog.csdn.net/jasonding1354/article/details/42125555?utm_source=tuicool&utm_medium=referral


figure()

A figure is the windows in the GUI that has "Figure #" as title. Figures are numbered starting from 1 as opposed to the normal Python way starting from 0. This is clearly MATLAB-style. There are several parameters that determine what the figure looks like:

ArgumentDefaultDescriptionnum1number of figurefigsizefigure.figsizefigure size in in inches (width, height)dpifigure.dpiresolution in dots per inchfacecolorfigure.facecolorcolor of the drawing backgroundedgecolorfigure.edgecolorcolor of edge around the drawing backgroundframeonTruedraw figure frame or not

The defaults can be specified in the resource file and will be used most of the time. Only the number of the figure is frequently changed.

When you work with the GUI you can close a figure by clicking on the x in the upper right corner. But you can close a figure programmatically by calling close. Depending on the argument it closes (1) the current figure (no argument), (2) a specific figure (figure number or figure instance as argument), or (3) all figures (all as argument).

As with other objects, you can set figure properties with the set_something methods.

转自 http://www.labri.fr/perso/nrougier/teaching/matplotlib/#figures-subplots-axes-and-ticks


subplot() 和 add_subplot()

subplot是为了在一张图里放多个子图,与Matlab里的subplot类似。

pyplot是一个有状态的对象,包含了当前的图,画图区域,等。

pyplot通过调用subplot或者add_subplot来增加子图,如p1 = plt.subplot(211) 或者 p1 = plt.subplot(2,1,1), 表示创建一个2行,1列的图,p1为第一个子图,然后在p1上画曲线,设置标注标题图例等,就可以使用p1来调用相关的函数,与pyplot相同的是,可以直接使用pyplot画图,添加label,等,也可以是使用p1来做这些事情。与pyplot不同的是,有一些函数的名字不太一样,添加坐标轴的标注的函数为set_xlabel和set_ylabel,添加标题set_title,只是给子图添加标题,由于pyplot是一个有状态的对象,所以pyplot.title也是给当前子图添加标题,如果要给整个图添加标题,可以使用pyplot.suptitle(text)。

转自 http://www.xuebuyuan.com/491377.html

==================我是matplotlib分割线==================

在输入以下代码时,


可能会提示: name 'array' is not defined ,这时可以输入以下代码以定义 array。

from array import array

继续输入之前的代码,会弹出以下提示: must be char, not list,

说明 array 的对象不符合指定格式,这时候需要做如下调整:

import numpy as npax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*np.array(datingLabels),15.0*np.array(datingLabels))


chapter 2.3.2 测试算法: 使用k-近邻算法识别手写数字

os.getcwd()
函数得到当前工作目录,即当前Python脚本工作的目录路径。

os.listdir()
返回指定目录下的所有文件和目录名。

>>> os.listdir(os.getcwd())['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe']>>>




0 0
原创粉丝点击