RTrees、Boost、ANN_MLP、KNearest、NormalBayesClassifier、SVM,大写英文字母识别,三目运算符的妙用(OpenCV案例源码letter_recog.cpp解读1)

letter_recog.cpp是ml.hpp的最佳案例,可以解读出样本集、机器学习的内容,所以写了两篇博客。

ml.hpp的整体理解,请拜读大神的文章,多读几遍。

【样本集】

1、文件的读取、保存,推荐用load()、save(),而不是read()、write()。

2、样本集有data(特征集)、responses(标签集)两部分,data必须是32FC1(32位浮点单通道)类型,responses必须是CV_32S类型(整型int,类型变量)或CV_32F(浮点型,序列变量)

【知识点1】
经典机器学习算法的应用:Random Trees classifier、Boosting classifier、MLP、Knearest、Nbayes、Support Vector Machines

由于MLP不支持类型变量的标签,所以使用序列变量的标签(如0、1组成的1*26的二进制一维向量,[1,0,0,…]指代A),关于序列变量参考此链接

由于Boosting classifier只能用于二分类问题,所以循环了很多次,如第一次分A和其他类,第二次分B和其他类。达到26分类目的。

【知识点2】
三目运算符的妙用,替代if……else if

//由上至下依次判断执行,代替了if……else if的嵌套
if ((method == 0 ? 
    bool型函数0 :
    method == 1 ?
    bool型函数1 :
    method == 2 ?
    bool型函数2 :
    method == 3 ?
    bool型函数3 :
    method == 4 ?
    bool型函数4 :
    method == 5 ?
    bool型函数5 :
    -1) < 0)

    return 0;

【数据集】letter-recognition.data,20000*17,前16000行用于训练,后4000行测试。

第1列为label,后16列为特征值(整数,被归一化到0~15范围,主要是统计矩和边缘计数),含义如下:
1. x-box horizontal position of box
2. y-box vertical position of box
3. width width of box
4. high height of box
5. onpix total # on pixels
6. x-bar mean x of on pixels in box
7. y-bar mean y of on pixels in box
8. x2bar mean x variance
9. y2bar mean y variance
10. xybar mean x y correlation
11. x2ybr mean of x * x * y
12. xy2br mean of x * y * y
13. x-ege mean edge count left to right
14. xegvy correlation of x-ege with y
15. y-ege mean edge count bottom to top
16. yegvx correlation of y-ege with x

 注意,MLP不支持类别标签A~Z,所以用int型代替,int cls_label = responses.at<int>(i) -'A';//大写英文字母转化为0~25。

案例中MLP训练时间超长,所以自己可以减少数据量。int ntrain_samples = (int)(nsamples_all*0.01);//只训练200个样本

 【具体代码分析】

 具体封装函数讲解read_num_class_data()、prepare_train_data()等(OpenCV案例源码letter_recog.cpp解读)

原文地址:https://www.cnblogs.com/xixixing/p/12504346.html