OpenCV 决策树 之 使用方法

本文介绍了使用OpenCV进行决策树训练和预测的基本流程,涉及CvDTreeSplit、CvDTreeNode、CvDTreeParams等核心结构。通过创建数据、训练决策树、预测和保存模型的实例,展示了决策树在OpenCV中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看OpenCV中与决策树有关的结构。

CvDTreeSplit 表示树节点的一个可能分割。

CvDTreeNode 表示决策树中的一个节点。

CvDTreeParams 包含了训练决策树的所有参数。

CvDTreeTrainData 决策树的训练数据,为树全体共享。

CvDTree 此类实现了决策树,包含了训练/预测等等操作。

就普通用户而言,使用的流程可以用准备数据、训练决策树、利用决策树预测三个环节表示。

下面这个小例子包括了数据的创建、训练、预测和保存几个基本步骤的简单操作。

#include "opencv2/core/core_c.h"
#include "opencv2/ml/ml.hpp"
#include <iostream>

int main()
{
    //init data
    float fdata[5][2] = {{1,1},{1,1},{1,0},{0,1},{0,1}};
    cv::Mat data(5,2,CV_32F,fdata);
    float fresponses[5] ={1,1,0,0,0};
    cv::Mat responses(5,1,CV_32F,fresponses);
    float priors[]={1,1};
    CvDTree *tree;
    CvDTreeParams params( 8, // max depth
                          1, // min sample count
                          0, // regression accuracy: N/A here
                          true, // compute surrogate split, as we have missing data
                          15, // max number of categories (use sub-optimal algorithm for larger numbers)
                          0, // the number of cross-validation folds
                          true, // use 1SE rule => smaller tree
                          true, // throw away the pruned tree branches
                          priors // the array of priors, the bigger p_weight, the more attention
                          // to the poisonous mushrooms
                          // (a mushroom will be judjed to be poisonous with bigger chance)
                          );
    tree = new CvDTree;
    tree->train (data,CV_ROW_SAMPLE,responses,cv::Mat(),
                 cv::Mat(),cv::Mat(),cv::Mat(),
                 params);
    
    //try predict
    cv::Mat sample(1,2,CV_32F,cv::Scalar::all (1));
    double r = tree->predict (sample,cv::Mat())->value;
    std::cout << "r: "<< r << std::endl;
    //save tree in the xml file
    tree->save ("tree.xml","test_tree");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值