统计学习方法第四章,贝叶斯估计的实现

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值