http://blog.csdn.net/xceman1997/article/details/7955349

http://www.cnblogs.com/yuyang-DataAnalysis/archive/2012/01/31/2333760.html

http://zhan.renren.com/dmeryuyang?gid=3602888497999161050&checked=true

http://blog.csdn.net/yanqingan/article/details/6125812

bool NaiveBayes::Train (const char * sFileSample, int iClassNum, int iFeaTypeNum,
string & sSegmenter, int iFeaExtractNum, const char * sFileModel, bool bCompactModel)
{
// 防御性代码
if (iClassNum <= 0 || iFeaTypeNum <= 0 || iFeaExtractNum <= 0)
return false;

ifstream in (sFileSample, ios_base::binary);
ofstream out (sFileModel);
if (!in || !out)
{
cerr << "Can not open the file" << endl;
return false;
}

// 这些都是临时数据结构,用来临时存储模型参数,特征选择需要的参数等等
// 1. the temp data structure for model parameters
// 1.1 the total number of document in training samples
int iTotalDocNum = 0;
// 1.2 the prior probability of class, temparaly it store the doc number in this class
double * pClassPriorProb = new double [iClassNum];
memset (pClassPriorProb, 0, iClassNum*sizeof(double));
// 1.3 the prior probability of feature type, temparaly it stores the doc number in this feature (这个主要用于特征选择,bayes模型本身并不需要这个参数)
double * pFeaItemPriorProb = new double [iFeaTypeNum];
memset (pFeaItemPriorProb, 0, iFeaTypeNum*sizeof(double));
// 1.4 the chi-square value that feature falls into class, temparaly it stores the doc number for this class and feature (可以看到,特征选择算法主要用卡方选择)
double ** ppChiMatrix = new double * [iClassNum];
for (int i=0; i<iClassNum; i++)
{
ppChiMatrix[i] = new double [iFeaTypeNum];
memset (ppChiMatrix[i], 0, iFeaTypeNum*sizeof(double));
}
// 1.5 the post-probability for class and feature
double ** ppPProbMatrix = new double * [iClassNum];
for (int i=0; i<iClassNum; i++)
{
ppPProbMatrix[i] = new double [iFeaTypeNum];
memset (ppChiMatrix[i], 0, iFeaTypeNum*sizeof(double));
}
// 1.6 for the feature selection (表示哪些特征被选中了)
int * pFeaSelected = new int [iFeaTypeNum];
memset (pFeaSelected, 0, iFeaTypeNum*sizeof(int));

// 2. iterate the training samples and fill count into the temp data structure
string sLine;
int i = 0;
while (getline (in, sLine))
{
// show some information on screen
if (0 == i%10000)
cout << i << "\n";
i++;

// 2.1 the total number of doc
iTotalDocNum++;

// 2.2 split the sample into class and feature items
string::size_type iSeg = sLine.find_first_of (sSegmenter);
string sTmp = sLine.substr (0, iSeg);
int iClassId = atoi (sTmp.c_str());
if (iClassId >= iClassNum)
continue;
pClassPriorProb [iClassId]++;

// 2.3 count the rest feature items
iSeg += sTmp.length();
sTmp = sLine.substr (iSeg);
istringstream isLine (sTmp);
string sTmpItem;
while (isLine >> sTmpItem)
{
int iFeaItemId = atoi (sTmpItem.c_str());
if (iFeaItemId >= iFeaTypeNum)
continue;
// add the count
pFeaItemPriorProb [iFeaItemId]++;
ppChiMatrix [iClassId][iFeaItemId]++;

}
}

// 3. calculate the model parameters
// 3.1 the chi-square value as well as the post-probabilty
for (int i=0; i<iClassNum; i++)
{
for (int j=0; j<iFeaTypeNum; j++)
{
double dA = ppChiMatrix[i][j];
double dB = pFeaItemPriorProb[j] - dA; // currently pFeaItemPriorProb[i] == sum_i (ppChiMatrix[i][j])
double dC = pClassPriorProb [i] - dA; // currently pClassPriorProb[i] == sum_j (ppChiMatrix[i][j])
double dD = (double)iTotalDocNum - dA - dB - dC;

// the chi value
double dNumerator = dA * dD;
dNumerator -= dB * dC;
dNumerator = pow (dNumerator, 2.0);
double dDenominator = dA + dB;
dDenominator *= (dC + dD);
dDenominator += DBL_MIN; // for smoothing
ppChiMatrix[i][j] = dNumerator / dDenominator;

// the post-probability: p(feature|class)
ppPProbMatrix[i][j] = dA / pClassPriorProb [i];
}
}

// 3.2 the prior probability of class
for (int i=0; i<iClassNum; i++)
pClassPriorProb [i] /= iTotalDocNum;

// 3.3 the prior probability of feature
for (int i=0; i<iFeaTypeNum; i++)
pFeaItemPriorProb [i] /= iTotalDocNum;

// 4. feature selection (这个函数下一篇文章再详细讲)
FeaSelByChiSquare (ppChiMatrix, ppPProbMatrix, iClassNum,
iFeaTypeNum, iFeaExtractNum, pFeaSelected);

// 5. dump the model into txt file

if (bCompactModel) // output the parameters only for predicting
{
// 5.1 the prior probability of class
out << iClassNum << endl;
for (int i=0; i<iClassNum; i++)
{
out << pClassPriorProb [i] << "\n";
}
// 5.2 the actual selected feature type number
int iActualFeaNum = 0;
for (int j=0; j<iFeaTypeNum; j++)
{
if (1 == pFeaSelected[j])
iActualFeaNum ++;
}
out << iActualFeaNum << endl;
// 5.3 the post probability
for (int i=0; i<iClassNum; i++)
{
for (int j=0; j<iFeaTypeNum; j++)
{
if (1 == pFeaSelected[j])
{
out << j << ":" << ppPProbMatrix[i][j] << "\n";
}
}
}
}
else // output the full information
{
// 5.1 the total number of document
out << iTotalDocNum << endl;

// 5.2 the prior probability of class
out << iClassNum << endl;
for (int i=0; i<iClassNum; i++) // classindex:priorprob
{
out << i << ":" << pClassPriorProb [i] << "\n";
}

// 5.3 the prior probability of feature type: this is NO used in bayes model, record this for more info
// and whether this feature is selected or not by any class
out << iFeaTypeNum << "\n";
for (int i=0; i<iFeaTypeNum; i++) // featureId:priorprob:selected or not
{
out << i << ":" << pFeaItemPriorProb[i] << ":" << pFeaSelected << "\n";
}

// 5.4 the chi-square value for class-feature pair
for (int i=0; i<iClassNum; i++)
{
for (int j=0; j<iFeaTypeNum; j++)
{
out << ppChiMatrix[i][j] << "\n";
}
}

// 5.5 the post probability
for (int i=0; i<iClassNum; i++)
{
for (int j=0; j<iFeaTypeNum; j++)
{
out << ppPProbMatrix[i][j] << "\n";
}
}
}

// last, release the memory
delete [] pClassPriorProb;
delete [] pFeaItemPriorProb;
for (int i=0; i<iClassNum; i++)
{
delete [] ppChiMatrix[i];
}
delete [] ppChiMatrix;
for (int i=0; i<iClassNum; i++)
{
delete [] ppPProbMatrix[i];
}
delete [] ppPProbMatrix;
delete [] pFeaSelected;

return true;
}

模式识别之线性判别---naive bayes朴素贝叶斯代码实现的更多相关文章

  1. Naive Bayes(朴素贝叶斯算法)[分类算法]

    Naïve Bayes(朴素贝叶斯)分类算法的实现 (1) 简介: (2)   算法描述: (3) <?php /* *Naive Bayes朴素贝叶斯算法(分类算法的实现) */ /* *把. ...

  2. PGM:贝叶斯网表示之朴素贝叶斯模型naive Bayes

    http://blog.csdn.net/pipisorry/article/details/52469064 独立性质的利用 条件参数化和条件独立性假设被结合在一起,目的是对高维概率分布产生非常紧凑 ...

  3. Python机器学习算法 — 朴素贝叶斯算法(Naive Bayes)

    朴素贝叶斯算法 -- 简介 朴素贝叶斯法是基于贝叶斯定理与特征条件独立假设的分类方法.最为广泛的两种分类模型是决策树模型(Decision Tree Model)和朴素贝叶斯模型(Naive Baye ...

  4. 【机器学习实战】第4章 朴素贝叶斯(Naive Bayes)

    第4章 基于概率论的分类方法:朴素贝叶斯 朴素贝叶斯 概述 贝叶斯分类是一类分类算法的总称,这类算法均以贝叶斯定理为基础,故统称为贝叶斯分类.本章首先介绍贝叶斯分类算法的基础——贝叶斯定理.最后,我们 ...

  5. 【Spark机器学习速成宝典】模型篇04朴素贝叶斯【Naive Bayes】(Python版)

    目录 朴素贝叶斯原理 朴素贝叶斯代码(Spark Python) 朴素贝叶斯原理 详见博文:http://www.cnblogs.com/itmorn/p/7905975.html 返回目录 朴素贝叶 ...

  6. NLP系列(4)_朴素贝叶斯实战与进阶

    作者: 寒小阳 && 龙心尘 时间:2016年2月. 出处:http://blog.csdn.net/han_xiaoyang/article/details/50629608 htt ...

  7. NLP系列(4)_朴素贝叶斯实战与进阶(转)

    http://blog.csdn.net/han_xiaoyang/article/details/50629608 作者: 寒小阳 && 龙心尘 时间:2016年2月. 出处:htt ...

  8. 一步步教你轻松学朴素贝叶斯模型算法Sklearn深度篇3

    一步步教你轻松学朴素贝叶斯深度篇3(白宁超   2018年9月4日14:18:14) 导读:朴素贝叶斯模型是机器学习常用的模型算法之一,其在文本分类方面简单易行,且取得不错的分类效果.所以很受欢迎,对 ...

  9. 统计学习方法——第四章朴素贝叶斯及c++实现

    1.名词解释 贝叶斯定理,自己看书,没啥说的,翻译成人话就是,条件A下的bi出现的概率等于A和bi一起出现的概率除以A出现的概率. 记忆方式就是变后验概率为先验概率,或者说,将条件与结果转换. 先验概 ...

随机推荐

  1. Js 常用函数【持续更新】

    Js Math对象方法介绍:http://www.w3school.com.cn/jsref/jsref_obj_math.asp 1. 算数函数(Math) 1)Js小数取整 常用于:分页算法 js ...

  2. 在ubuntu16.4中为pycharm创建桌面快捷启动方式

    在ubuntu环境中每次使用pycharm需要到它的安装目录中执行./pycharm.sh来启动pycharm.比较麻烦,既然ubuntu提供了桌面环境我们应该从分利用.哈哈哈... 上干货 我的py ...

  3. python中杂乱问题

    1 字符串格式化中的格式指定 format_spec ::= [[fill]align][sign][#][][width][,][.precision][type] fill ::= <any ...

  4. mysql-5.7 收缩系统表空间详解

    innodb 系统表空间是一个逻辑上的概念,它的物理表现就是innodb系统表空间文件:在讲扩展系统表空间时我们说到 可以用增加文件,增加autoextend标记 这两种方式来解决:但是问题到了收缩表 ...

  5. [Jobdu] 题目1516:调整数组顺序使奇数位于偶数前面

    题目描述: 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变. 输入: 每个输 ...

  6. 用rfkill命令管理蓝牙和wifi

    rfkill是一个内核级别的管理工具,可以打开和关闭设备的蓝牙和wifi. #列出所有可用设备rfkill list 输出如下:0: phy0: Wireless LAN    Soft blocke ...

  7. 网络编程----------SOCKET编程实现简单的TCP协议

    首先我们须要大致了解TCP的几点知识: 1.TCP的特点:面向连接的可靠性传输 2.TCP的三次握手建立连接和四次挥手释放连接.但为什么TCP要三次握手建立连接呢? 答:由于两次握手无法保证可靠性.若 ...

  8. Django2.1更新日志

    前两天本来想把2.1的release note做个中文摘要,后来发现没什么大的改动. 不过更新以后还是发下一个bug,或者是已经feature本身的改动,就是QueryDict这个类的实例不能再往里放 ...

  9. hdoj1171 Big Event in HDU

    Big Event in HDU Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  10. js正则表达式判断一个字符串是否是正确的有数字和小数点组成的金钱形式和 判读数值类型的正则表达式

    function checkRates(str){    var re = /^(([1-9][0-9]*\.[0-9][0-9]*)|([0]\.[0-9][0-9]*)|([1-9][0-9]*) ...