#include<iostream>
#include<list>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<sstream>
#include<iomanip>
#include<cmath>
#include<fstream>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
class Bayes
{
private:
vector<string> attribute;
vector<vector<string>>data;
double GetPosPrior()
{
int count=0;
for(vector<vector<string>>::iterator iter=data.begin();iter!=data.end();++iter)
{
if((*iter)[4]=="yes")
count++;
}
return (double)count/data.size();
}
double GetNegPrior()
{
int count=0;
for(vector<vector<string>>::iterator iter=data.begin();iter!=data.end();++iter)
{
if((*iter)[4]=="no")
count++;
}
return (double)count/data.size();
}
// 求条件概率
double ConPro(int attr,string value,bool pos)
{
if(pos)
{
int count1=0,count2=0;
for(vector<vector<string>>::iterator iter=data.begin();iter!=data.end();++iter)
{
if((*iter)[4]=="yes")
{
count1++;
if((*iter)[attr]==value)
count2++;
}
}
return (double)count2/(count1);
}
else
{
int count1=0,count2=0;
for(vector<vector<string>>::iterator iter=data.begin();iter!=data.end();++iter)
{
if((*iter)[4]=="no")
{
count1++;
if((*iter)[attr]==value)
count2++;
}
}
return (double)count2/(count1);
}
}
public:
Bayes()
{
// 从文件中加载数据
ifstream in("playData.txt");
if(in==NULL)
{
cout<<"fail to open file!"<<endl;
return;
}
string line,str;
getline(in,line);
istringstream istring(line);
while(!istring.eof())
{
istring>>str;
attribute.push_back(str);
}
while(!in.eof())
{
getline(in,line);
vector<string> vecStr;
istringstream istring(line);
while(!istring.eof())
{
istring>>str;
vecStr.push_back(str);
}
data.push_back(vecStr);
}
in.close();
}
// 传递4个元组的例子
string run(string a[])// 返回贝叶斯的预测结果
{
string result;
double posPr=this->GetPosPrior();
double negPr=this->GetNegPrior();
for(int i=0;i<4;i++)
{
posPr*=ConPro(i,a[i],true);
negPr*=ConPro(i,a[i],false);
}
if(posPr>negPr)
result="yes";
else
result="no";
return result;
}
};
string out[]={"sunny","overcast","rainy"};
string temp[]={"hot","mild"};
string humidity[]={"high","hot","normal"};
string windy[]={"TRUE","FALSE"};
string *s[]={out,temp,humidity,windy};
void writeAll()
{
}
int main()
{
Bayes bay;
string ex[4];
cin>>ex[0]>>ex[1]>>ex[2]>>ex[3];
cout<<"分类的结果:";
cout<<bay.run(ex);
system("pause");
return 0;
}