OpenCV机器学习(6)朴素贝叶斯分类器(Naive Bayes Classifier)cv::ml::NormalBayesClassifier的使用

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

cv::ml::NormalBayesClassifier 是 OpenCV 机器学习模块中的一部分,用于实现朴素贝叶斯分类器(Naive Bayes Classifier)。这种分类器基于贝叶斯定理,并假设特征之间相互独立(即"朴素"的假设),尽管这个假设在实际应用中往往不成立,但朴素贝叶斯分类器在很多情况下仍然表现良好,特别是在文本分类、垃圾邮件过滤等领域。

主要特点

  • 简单且快速:训练和预测过程都非常高效。
  • 适用于多分类问题:可以处理两个或更多类别的分类任务。
  • 基于概率的决策:为每个类别计算后验概率,并选择具有最高概率的类别作为预测结果。

常用成员函数

以下是一些常用的 cv::ml::NormalBayesClassifier 类成员函数:

  • 创建模型实例
    • Ptr create():创建一个新的 NormalBayesClassifier 模型实例。
  • 训练模型
    • train(const Ptr& trainData, int flags=0):使用提供的训练数据进行训练。
    • train(InputArray samples, int layout, InputArray responses):另一种形式的训练函数,直接接受样本和响应矩阵作为输入。
  • 预测
    • predict(InputArray samples, OutputArray results=noArray(), int flags=0) const:对新样本进行预测,并返回每个样本的类别标签或概率值(取决于标志)。
  • 保存与加载模型
    • save(const String& filename):将模型保存到文件。
    • load(const String& filename):从文件加载模型。

使用步骤

  • 准备数据:准备好你的训练数据集,包括特征向量及其对应的标签。
  • 初始化 NormalBayesClassifier 模型:使用 cv::ml::NormalBayesClassifier::create() 创建一个新的 NormalBayesClassifier 模型实例。
  • 训练模型:调用 train() 方法,传入你的训练数据来进行模型训练。
  • 评估模型:可以通过交叉验证或者在独立的测试集上评估模型性能。
  • 预测新数据:使用训练好的模型对新的未见过的数据进行预测,并获取其所属类别的概率分布。

代码示例

cpp 复制代码
#include <iostream>
#include <opencv2/ml.hpp>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace cv::ml;
using namespace std;

int main()
{
    // 准备训练数据
    Mat samples = ( Mat_< float >( 4, 2 ) << 0.5, 1.0, 1.0, 1.5, 2.0, 0.5, 1.5, 0.0 );

    Mat responses = ( Mat_< int >( 4, 1 ) << 0, 0, 1, 1 );

    // 确保数据和标签是浮点数类型
    if ( samples.type() != CV_32F )
    {
        samples.convertTo( samples, CV_32F );
    }
    if ( responses.type() != CV_32S )
    {  // 注意:对于分类,通常使用整数类型标签
        responses.convertTo( responses, CV_32S );
    }

    // 创建并配置 NormalBayesClassifier 模型
    Ptr< NormalBayesClassifier > nb_model = NormalBayesClassifier::create();

    // 训练模型
    bool ok = nb_model->train( samples, ROW_SAMPLE, responses );
    if ( ok )
    {
        // 保存模型
        nb_model->save( "nb_model.yml" );

        // 对新样本进行预测
        Mat sample     = ( Mat_< float >( 1, 2 ) << 1.6, 0.7 );
        float response = nb_model->predict( sample );

        cout << "The predicted response for the sample is: " << response << endl;
    }
    else
    {
        cerr << "Training failed!" << endl;
    }

    return 0;
}

运行结果

bash 复制代码
The predicted response for the sample is: 1
相关推荐
AAA小肥杨12 分钟前
2025人工智能AI新突破:PINN内嵌物理神经网络火了
人工智能·深度学习·神经网络·ai·大模型部署
梓羽玩Python1 小时前
太牛了!OWL:Manus 最强开源复现,开源框架GAIA基准测试中排第一!
人工智能·python
二川bro1 小时前
TensorFlow.js 全面解析:在浏览器中构建机器学习应用
javascript·机器学习·tensorflow
dearxue1 小时前
「新」AI Coding(Agent) 的一点总结和看法
机器学习·aigc
詹天佐1 小时前
ICCE 数字车钥匙介绍
人工智能·算法
坚果的博客1 小时前
uniapp版本加密货币行情应用
人工智能·华为·uni-app·harmonyos
goomind2 小时前
深度学习实战车辆目标跟踪与计数
人工智能·深度学习·目标跟踪·pyqt5·bytetrack·deepsort·撞线计数
金智维科技2 小时前
什么是AI Agent的自学习能力?
人工智能