根據(jù)《統(tǒng)計(jì)學(xué)習(xí)方法》以例4.1的數(shù)據(jù)為例實(shí)現(xiàn)的樸素貝葉斯漂辐。
感覺(jué)最后計(jì)算比較時(shí)候可以避免使用double,但是為了思路清晰就這樣把。
#include<iostream>
#include<map>
using namespace std;
int X1[]{1,1,1,1,1,2,2,2,2,2,3,3,3,3,3};
char X2[]{'S','M','M','S','S','S','M','M','L','L','L','M','M','L','L'};
int Y[]{-1,-1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1};
int main() {
int x1;
char x2{};
cin >> x1;
cin >> x2;
map<string, int> ycount;//記錄y =1 -1的次數(shù)
map<string, int> x1count1;//記錄y=1,-1 ,x1匹配的次數(shù)
map<string, int> x2count1;//記錄y=1,-1 ,x2匹配的次數(shù)
for (int i = 0; i < sizeof(Y) / sizeof(Y[0]); i++) {
if (Y[i] == 1) {
ycount["y=1"] ++;
if (X1[i] == x1) {
x1count1["y=1"] ++;
}
if (X2[i] == x2) {
x2count1["y=1"] ++;
}
}
else {
ycount["y=-1"] ++;
if (X1[i] == x1) {
x1count1["y=-1"] ++;
}
if (X2[i] == x2) {
x2count1["y=-1"] ++;
}
}
}
//計(jì)算概率
double rs1 = (double)ycount["y=1"]/15 * (double)x1count1["y=1"]/ (double)ycount["y=1"] * (double)x2count1["y=1"]/ (double)ycount["y=1"];
double rs2 = (double)ycount["y=-1"] /15 * (double)x1count1["y=-1"] / (double)ycount["y=-1"] * (double)x2count1["y=-1"] / (double)ycount["y=-1"];
cout << rs1<<endl;
cout << rs2<<endl;
(rs1 > rs2) ? cout << "y=1" : cout << "y=-1";
system("pause");
}