com.davidbracewell.ml.classification.bayes.BernoulliNaiveBayes.java Source code

Java tutorial

Introduction

Here is the source code for com.davidbracewell.ml.classification.bayes.BernoulliNaiveBayes.java

Source

/*
 * (c) 2005 David B. Bracewell
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.davidbracewell.ml.classification.bayes;

import com.davidbracewell.ml.Instance;
import com.davidbracewell.ml.classification.ClassificationResult;
import org.apache.commons.math3.util.FastMath;

/**
 * @author David B. Bracewell
 */
public class BernoulliNaiveBayes extends NaiveBayes {

    private static final long serialVersionUID = 1L;

    @Override
    protected ClassificationResult classifyImpl(Instance instance) {
        int numClasses = getTargetFeature().alphabetSize();
        double[] probabilities = new double[numClasses];
        double sum = 0d;
        for (int i = 0; i < numClasses; i++) {
            probabilities[i] = FastMath.log10(priors[i]);
            for (int f = 0; f < getFeatures().size(); f++) {
                if (instance.isDefined(f)) {
                    probabilities[i] += FastMath.log10(conditionals[f][i]);
                } else {
                    probabilities[i] += FastMath.log10(1 - conditionals[f][i]);
                }
            }

            probabilities[i] = Math.exp(probabilities[i]);
            sum += probabilities[i];
        }

        //normalize to make probabilities add to one
        for (int i = 0; i < numClasses; i++) {
            probabilities[i] = probabilities[i] / sum;
        }

        return new ClassificationResult(getTargetFeature(), probabilities);
    }

}//END OF NaiveBayes2