统计学习方法第四章,贝叶斯估计的实现
来源:互联网 发布:知乎炸鱼 编辑:程序博客网 时间:2024/04/20 07:38
#include<iostream>#include<vector>using namespace std;const int r=1; const int N=15;//训练样本个数 const int K=2;//类标记数const int M=3;//特征可能取值数const int S=2;//特征维数int array[3][N]={1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 2, 2, 1, 1, 1, 2, 2, 3, 3, 3, 2, 2, 3, 3,-1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1};float A[K];float B[K][M];//记录第一维特征的取值与其相应的类的概率float C[K][M];//记录第二维特征的取值与其相应的类的概率int main(){ int count1=0,count2=0; int count3[S][M];// y=-1 int count4[S][M];//y=1; for(int i=0;i<S;i++) for(int j=0;j<M;j++) { count3[i][j]=0; count4[i][j]=0; } for(int i=0;i<15;i++) { if(array[2][i]==-1){ count1++; for(int j=0;j<2;j++){ if(array[j][i]==1) {count3[j][0]++;} else if(array[j][i]==2) {count3[j][1]++;} else if(array[j][i]==3) count3[j][2]++; } } else if(array[2][i]==1) { count2++; for(int j=0;j<2;j++) { if(array[j][i]==1) count4[j][0]++; else if(array[j][i]==2) count4[j][1]++; else if(array[j][i]==3) count4[j][2]++; } } } cout<<count1<<endl; cout<<count2<<endl; for(int i=0;i<2;i++) for(int j=0;j<3;j++) cout<<count3[i][j]; cout<<endl; A[0]=float(count1+r)/(N+K); A[1]=float(count2+r)/(N+K); cout<<A[0]<<endl; cout<<A[1]<<endl; for(int j=0;j<M;j++) { B[0][j]=float(count3[0][j]+r)/(count1+M*r); C[0][j]=float(count3[1][j]+r)/(count1+M*r); } for(int j=0;j<M;j++) { B[1][j]=float(count4[0][j])/count2; C[1][j]=float(count4[1][j])/count2; } int x1=0; cout<<"enter x(1):from 1 to 3:\n"; int x2=0; char c; cin>>x1; cout<<"enter x(2):from s m l:\n"; cin>>c; switch(c){ case 's':x2=1;break; case 'm':x2=2;break; case 'l':x2=3;break; } cout<<(A[0]*B[0][x1-1]*C[0][x2-1])<<endl; // cout<<A[0]<<endl; // cout<<B[0][x1-1]<<endl; // cout<<C[0][x2-1]<<endl; // cout<<(A[1]*B[1][x1-1]*C[1][x2-1])<<endl; if((A[0]*B[0][x1-1]*C[0][x2-1])>(A[1]*B[1][x1-1]*C[1][x2-1])) cout<<"y= -1"<<endl; else cout<<"y= 1 "<<endl; return 0;}