Пример #1
0
/* Do inference ------------------------------------------------------------ */
int NaiveBayes::doInference(const MultidimArray<double> &newFeatures, double &cost,
                            Matrix1D<double> &classesProbs, Matrix1D<double> &allCosts)
{
    classesProbs=__priorProbsLog10;
    for(int f=0; f<Nfeatures; f++)
    {
        const LeafNode &leaf_f=*(__leafs[f]);
        double newFeatures_f=DIRECT_A1D_ELEM(newFeatures,f);
        for (int k=0; k<K; k++)
        {
            double p = leaf_f.assignProbability(newFeatures_f, k);

            if (fabs(p) < 1e-2)
                VEC_ELEM(classesProbs,k) += -2*DIRECT_A1D_ELEM(__weights,f);
            else
                VEC_ELEM(classesProbs,k) += DIRECT_A1D_ELEM(__weights,f)*std::log10(p);

#ifdef DEBUG_FINE_CLASSIFICATION

            if(debugging == true)
            {
                std::cout << "Feature " << f
                << " Probability for class " << k << " = "
                << classesProbs(k) << " increase= " << p
                << std::endl;
                char c;
                // COSS                    std::cin >> c;
                //                    if (c=='q') debugging = false;
            }
#endif

        }
    }

    classesProbs-=classesProbs.computeMax();
    //    std::cout << "classesProbs " << classesProbs.transpose() << std::endl;

    for (int k=0; k<K; k++)
        VEC_ELEM(classesProbs,k)=pow(10.0,VEC_ELEM(classesProbs,k));
    classesProbs*=1.0/classesProbs.sum();
    //    std::cout << "classesProbs norm " << classesProbs.transpose() << std::endl;

    allCosts=__cost*classesProbs;
    //    std::cout << "allCosts " << allCosts.transpose() << std::endl;

    int bestk=0;
    cost=VEC_ELEM(allCosts,0)=std::log10(VEC_ELEM(allCosts,0));
    for (int k=1; k<K; k++)
    {
        VEC_ELEM(allCosts,k)=std::log10(VEC_ELEM(allCosts,k));
        if (VEC_ELEM(allCosts,k)<cost)
        {
            cost=VEC_ELEM(allCosts,k);
            bestk=k;
        }
    }

#ifdef DEBUG_CLASSIFICATION
    if(debugging == true)
    {
        for (int k=0; k<K; k++)
            classesProbs(k)=log10(classesProbs(k));
        std::cout << "Class probababilities=" << classesProbs.transpose()
        << "\n  costs=" << allCosts.transpose()
        << "  best class=" << bestk << " cost=" << cost << std::endl;
        char c;
        // COSS std::cin >> c;
        // if (c=='q') debugging = false;
    }
#endif
    return bestk;
}