根据《统计学习方法》以例4.1的数据为例实现的朴素贝叶斯。
感觉最后计算比较时候可以避免使用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的次数
map<string, int> x1count1;//记录y=1,-1 ,x1匹配的次数
map<string, int> x2count1;//记录y=1,-1 ,x2匹配的次数
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"] ++;
}
}
}
//计算概率
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");
}