001    /*
002     * Copyright (C) 2008-2009 Holger Arndt, A. Naegele and M. Bundschus
003     *
004     * This file is part of the Java Data Mining Package (JDMP).
005     * See the NOTICE file distributed with this work for additional
006     * information regarding copyright ownership and licensing.
007     *
008     * JDMP is free software; you can redistribute it and/or modify
009     * it under the terms of the GNU Lesser General Public License as
010     * published by the Free Software Foundation; either version 2
011     * of the License, or (at your option) any later version.
012     *
013     * JDMP is distributed in the hope that it will be useful,
014     * but WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016     * GNU Lesser General Public License for more details.
017     *
018     * You should have received a copy of the GNU Lesser General Public
019     * License along with JDMP; if not, write to the
020     * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
021     * Boston, MA  02110-1301  USA
022     */
023    
024    package org.jdmp.core.algorithm.classification.bayes;
025    
026    import org.jdmp.core.algorithm.classification.AbstractClassifier;
027    import org.jdmp.core.algorithm.classification.Classifier;
028    import org.jdmp.core.algorithm.estimator.DensityEstimator;
029    import org.jdmp.core.algorithm.estimator.DiscreteDensityEstimator;
030    import org.jdmp.core.dataset.RegressionDataSet;
031    import org.jdmp.core.sample.ClassificationSample;
032    import org.ujmp.core.Matrix;
033    import org.ujmp.core.MatrixFactory;
034    import org.ujmp.core.calculation.Calculation.Ret;
035    import org.ujmp.core.exceptions.MatrixException;
036    
037    public class NaiveBayesClassifier extends AbstractClassifier {
038    
039            private static final long serialVersionUID = -6511197233753905836L;
040    
041            private DensityEstimator[][] dists = null;
042    
043            private DensityEstimator classDists = null;
044    
045            private int classCount = 0;
046    
047            // private double[][][] conditionals = null;
048    
049            // private double[] classDist = null;
050    
051            public NaiveBayesClassifier() {
052                    super();
053            }
054    
055            @Override
056            public Matrix predict(Matrix input, Matrix sampleWeight) throws Exception {
057                    double[] logs = new double[classCount];
058                    // for all classes
059                    for (int i = 0; i < classCount; i++) {
060                            // for all features
061                            logs[i] = Math.log(classDists.getProbability(i));
062                            for (int j = 0; j < input.getColumnCount(); j++) {
063                                    int val = (int) input.getAsDouble(0, j);
064                                    logs[i] += Math.log(dists[j][i].getProbability(val));
065                            }
066                    }
067                    double[] probs = logToProbs(logs);
068                    Matrix m = MatrixFactory.zeros(1, 2);
069                    m.setAsDouble(probs[0], 0, 1);
070                    m.setAsDouble(probs[1], 0, 0);
071                    return m;
072                    // Matrix r=MatrixFactory.fromArray(probs).transpose();
073            }
074    
075            /**
076             * @todo Put in common class!
077             * @param logs
078             * @return
079             */
080            public static double[] logToProbs(double[] logs) {
081                    double[] probs = new double[logs.length];
082                    double sum = 0.0;
083                    for (int i = 0; i < probs.length; i++) {
084                            probs[i] = Math.exp(logs[i]);
085    
086                            sum += probs[i];
087                    }
088                    for (int i = 0; i < probs.length; i++) {
089                            probs[i] = probs[i] / sum;
090                    }
091                    return probs;
092            }
093    
094            @Override
095            public void reset() throws Exception {
096                    // TODO Auto-generated method stub
097    
098            }
099    
100            @Override
101            public void train(RegressionDataSet dataSet) throws Exception {
102                    // classCount = ((ClassificationDataSet) dataSet).getClassCount();
103                    classCount = 2;
104                    int featureCount = dataSet.getFeatureCount();
105    
106                    Matrix dataSetInput = dataSet.getInputMatrix();
107    
108                    Matrix max = dataSetInput.max(Ret.NEW, Matrix.ROW);
109    
110                    this.dists = new DensityEstimator[featureCount][classCount];
111                    this.classDists = new DiscreteDensityEstimator(classCount, true);
112    
113                    for (int i = 0; i < featureCount; i++) {
114                            for (int j = 0; j < classCount; j++) {
115                                    dists[i][j] = new DiscreteDensityEstimator((int) max.getAsDouble(0, i) + 1, true);
116                            }
117                    }
118    
119                    // go over all samples an count
120                    for (int i = 0; i < dataSet.getSamples().getSize(); i++) {
121                            ClassificationSample s = (ClassificationSample) dataSet.getSamples().getElementAt(i);
122                            Matrix sampleInput = s.getMatrix(INPUT);
123                            Matrix sampleTarget = s.getMatrix(TARGET);
124                            double weight = 1.0;
125                            Matrix w = s.getMatrix(WEIGHT);
126                            if (w != null) {
127                                    weight = w.doubleValue();
128                            }
129                            int outputVal = (int) sampleTarget.getAsDouble(0, 0);
130                            for (int j = 0; j < sampleInput.getColumnCount(); j++) {
131                                    int inputVal = (int) sampleInput.getAsDouble(0, j);
132                                    dists[j][outputVal].addValue(inputVal, weight);
133                            }
134                            classDists.addValue(outputVal, weight);
135                    }
136    
137            }
138    
139            @Override
140            public void train(Matrix input, Matrix sampleWeight, Matrix targetOutput) throws Exception {
141                    throw new MatrixException("sample by sample learning is not supported");
142            }
143    
144            public Classifier emptyCopy() {
145                    return new NaiveBayesClassifier();
146            }
147    
148    }