C + + Description:
1#include <iostream>2#include <string>3#include <fstream>4#include <sstream>5#include <vector>6#include <map>7#include <Set>8 9 using namespacestd;Ten One classNaivebayes { A Public: - voidLoad_data (stringpath); - voidTrain_model (); the intPredictConstvector<int> &item); - Private: -vector<vector<int>>data; -map<pair<int,int,Double> c_p;//conditional Prob +map<int,Double> p_p;//Prior prob - }; + A voidNaivebayes::load_data (stringpath) { at ifstream Fin (PATH.C_STR ()); - if(!Fin) { -Cerr <<"Open File Error"<<Endl; -Exit1); - } - in stringLine ; - while(Getline (Fin, line)) { to if(Line.size () >1) { + stringstream sin (line); - intElem; thevector<int>tmp; * while(Sin >>elem) { $ Tmp.push_back (elem);Panax Notoginseng } - Data.push_back (TMP); the } + } A fin.close (); the } + - voidNaivebayes::train_model () { $ for(Auto &d:data) { $ intLen =d.size (); -P_p[d[len-1]] += (1.0/data.size ()); - } the - for(Auto &p:p_p) {Wuyi intLabel =P.first; the DoublePrior =P.second; - for(Auto &d:data) { Wu for(inti =0; I < d.size (); ++i) { -C_p[make_pair (D[i], label)] + = (1.0/(Prior *data.size ())); About } $ } - } - } - A intNaivebayes::p redict (Constvector<int> &Item) { + intresult; the DoubleMax_prob =0.0; - for(Auto &p:p_p) { $ intLabel =P.first; the DoublePrior =P.second; the DoubleProb =Prior; the for(inti =0; I < item.size ()-1; ++i) { theProb *=C_p[make_pair (Item[i], label)]; - } in the if(Prob >Max_prob) { theMax_prob =prob; Aboutresult =label; the } the } the + returnresult; - } the Bayi intMain () { the Naivebayes Naive_bayes; theNaive_bayes.load_data (string("Result.txt")); - Naive_bayes.train_model (); - thevector<int> item{2,4}; thecout <<naive_bayes.predict (item); the return 0; the}
Data set:
1 4-11 5-11 5 11 4 11 4-12 4-12 5-12 5 12 6 12 6 13 6 13 5 13 5 13 6 13 6-1
[Machine learning] Naive Bayes (Naivebayes)