- 操作系統: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() 方法,傳入你的訓練數據來進行模型訓練。
- 評估模型:可以通過交叉驗證或者在獨立的測試集上評估模型性能。
- 預測新數據:使用訓練好的模型對新的未見過的數據進行預測,并獲取其所屬類別的概率分布。
代碼示例
#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;
}
運行結果
The predicted response for the sample is: 1