机器学习系列(二)k-近邻算法(3)

来源:互联网 发布:装系统需要网络吗 编辑:程序博客网 时间:2024/04/27 22:15

本文重现书中2.3节示例,手写识别系统。

虽然是手写识别,但是简化来看,书中描述的其实是一个分类标签有十个(0-9),而特征向量有32*32=1024个的简单分类问题。我们都知道手写识别算法并没有如此简单,因此,对于本文所采用的方法,或者也可以说起了个“手写识别”的名字,而非手写识别的示例,大家尽可不必吐槽。

话不多说,先介绍数据。本示例采用的数据在github上的digits文件夹,包含训练集数据和测试集数据。可以看到,数据由一个个txt文件构成,文件名的第一个数字为该数据集对应标签,下划线后的数字对应为该标签的第n个数据。文件中的数据只包含0和1,因此无需进行归一化。

为了在Matlab中实现k-近邻算法,首先应当将数据读入矩阵,然后将矩阵输入分类函数进行测试。整个过程代码如下

clc;clear;%导入训练集数据及训练集标签trainingDataFolder = 'D:\matlab workspace\MachineLearning\kNN\digits\trainingDigits';trainingDataFiles = dir([trainingDataFolder '\*.txt']);for i = 1:length(trainingDataFiles)    name{i,1} = trainingDataFiles(i).name;    trainingLabels(i,1) = name{i,1}(1);    [a1] = textread(strcat(trainingDataFolder,'\',name{i,1}),'%s');    for j = 1:length(a1)        for k = 1:length(a1)            trainingData(i,32*(j-1)+k) = a1{j}(k);        end    endend%导入测试集数据及测试集标签testDataFolder = 'D:\matlab workspace\MachineLearning\kNN\digits\testDigits';testDataFiles = dir([testDataFolder '\*.txt']);for i = 1:length(testDataFiles)    name{i,1} = testDataFiles(i).name;    testLabels(i,1) = name{i,1}(1);    [a2] = textread(strcat(testDataFolder,'\',name{i,1}),'%s');    for j = 1:length(a2)        for k = 1:length(a2)            testData(i,32*(j-1)+k) = a2{j}(k);        end    endend%测试分类器errorCount = 0;for i = 1 : length(testLabels)    classifierResult(i,1) = classify0(testData(i,:),trainingData,trainingLabels,3);%     fprintf('Output:%c,Original:%c\n',classifierResult(i,1),testLabels(i));    if ~strcmp(classifierResult(i),testLabels(i))        errorCount = errorCount + 1;    endenderrorRate = errorCount/length(testLabels);
测试的errorRate = 1.37%。整个源码(Matlab)及数据均可在本人github(https://github.com/guankaer/kNN)上查看。