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.dataset;
025    
026    import java.util.ArrayList;
027    import java.util.Collections;
028    import java.util.HashMap;
029    import java.util.List;
030    import java.util.Map;
031    import java.util.Random;
032    
033    import org.jdmp.core.sample.ClassificationSample;
034    import org.jdmp.core.sample.Sample;
035    import org.jdmp.core.util.ObservableList;
036    import org.jdmp.core.variable.Variable;
037    import org.jdmp.core.variable.VariableFactory;
038    import org.ujmp.core.Matrix;
039    import org.ujmp.core.MatrixFactory;
040    import org.ujmp.core.exceptions.MatrixException;
041    import org.ujmp.core.util.MathUtil;
042    
043    public class ClassificationDataSet extends RegressionDataSet {
044            private static final long serialVersionUID = 3969274321783319184L;
045    
046            public static final String ACCURACY = "Accuracy";
047    
048            public static final String CONFUSION = "Confusion";
049    
050            public static final String ERRORCOUNT = "ErrorCount";
051    
052            public Matrix getClassDistribution() {
053                    Matrix m = MatrixFactory.zeros(getClassCount(), 1);
054    
055                    Map<Integer, Double> map = new HashMap<Integer, Double>();
056    
057                    for (Sample s : getSamples()) {
058                            int c = ((ClassificationSample) s).getTargetClass();
059                            Double d = map.get(c);
060                            if (d == null) {
061                                    d = 0.0;
062                            }
063                            d++;
064                            map.put(c, d);
065                    }
066    
067                    for (int i = 0; i < getClassCount(); i++) {
068                            Double d = map.get(i);
069                            if (d == null) {
070                                    d = 0.0;
071                            }
072                            m.setAsDouble(d / getSamples().getSize(), i, 0);
073                    }
074                    return m;
075            }
076    
077            public double getEarlyStoppingErrorCount(int numberOfSteps) {
078                    int index = getEarlyStoppingIndex(numberOfSteps);
079                    if (index >= 0) {
080                            return getErrorCountVariable().getMatrix(index).doubleValue();
081                    }
082                    return -1;
083            }
084    
085            public ClassificationDataSet() {
086                    super();
087                    getVariables().put(ACCURACY, VariableFactory.labeledVariable("Accuracy", 10000));
088                    getVariables().put(CONFUSION, VariableFactory.labeledVariable("Confusion", 1000));
089                    getVariables().put(ERRORCOUNT, VariableFactory.labeledVariable("Error Count", 10000));
090            }
091    
092            @Override
093            public ClassificationDataSet clone() {
094                    ClassificationDataSet ds = new ClassificationDataSet();
095                    for (Sample s : getSamples()) {
096                            ds.getSamples().add(s.clone());
097                    }
098                    return ds;
099            }
100    
101            public int getClassCount() {
102                    return (int) getSamples().getElementAt(0).getMatrix(Sample.TARGET).getColumnCount();
103            }
104    
105            public Variable getConfusionVariable() {
106                    return getVariables().get(CONFUSION);
107            }
108    
109            public Variable getErrorCountVariable() {
110                    return getVariables().get(ERRORCOUNT);
111            }
112    
113            public int getErrorCount() throws MatrixException {
114                    return (int) getErrorCountVariable().getMatrix().doubleValue();
115            }
116    
117            public Variable getAccuracyVariable() {
118                    return getVariables().get(ACCURACY);
119            }
120    
121            public void appendConfusionMatrix(Matrix m) {
122                    getConfusionVariable().addMatrix(m);
123            }
124    
125            public void appendAccuracyMatrix(Matrix m) {
126                    getAccuracyVariable().addMatrix(m);
127            }
128    
129            public void appendErrorCountMatrix(Matrix m) {
130                    getErrorCountVariable().addMatrix(m);
131            }
132    
133            public double getAccuracy() throws MatrixException {
134                    return getAccuracyVariable().getMatrix().doubleValue();
135            }
136    
137            public double getMaxAccuracy() throws MatrixException {
138                    return getAccuracyVariable().getAsMatrix().getMaxValue();
139            }
140    
141            public List<ClassificationDataSet> splitByClass() {
142                    List<ClassificationDataSet> returnDataSets = new ArrayList<ClassificationDataSet>();
143    
144                    for (int i = 0; i < getClassCount(); i++) {
145                            ClassificationDataSet ds = DataSetFactory.classificationDataSet("Class " + i);
146                            for (Sample s : getSamples()) {
147                                    if (((ClassificationSample) s).getTargetClass() == i) {
148                                            ds.getSamples().add(s.clone());
149                                    }
150                            }
151                            returnDataSets.add(ds);
152                    }
153    
154                    return returnDataSets;
155            }
156    
157            public List<ClassificationDataSet> splitForStratifiedCV(int numberOfCVSets, int idOfCVSet,
158                            long randomSeed) {
159                    List<ClassificationDataSet> returnDataSets = new ArrayList<ClassificationDataSet>();
160                    Random rand = new Random(randomSeed);
161                    int classCount = getClassCount();
162    
163                    // create empty lists
164                    List<List<Sample>> sortedSamples = new ArrayList<List<Sample>>();
165                    for (int i = 0; i < classCount; i++) {
166                            sortedSamples.add(new ArrayList<Sample>());
167                    }
168    
169                    // add samples to lists according to class
170                    for (Sample s : getSamples()) {
171                            int targetClass = ((ClassificationSample) s).getTargetClass();
172                            sortedSamples.get(targetClass).add(s);
173                    }
174    
175                    // shuffle lists
176                    Collections.shuffle(sortedSamples, rand);
177                    for (int i = 0; i < classCount; i++) {
178                            Collections.shuffle(sortedSamples.get(i), rand);
179                    }
180    
181                    // create sample lists
182                    List<List<Sample>> cvSets = new ArrayList<List<Sample>>();
183                    for (int cvSet = 0; cvSet < numberOfCVSets; cvSet++) {
184                            List<Sample> samples = new ArrayList<Sample>();
185                            cvSets.add(samples);
186                    }
187    
188                    // distribute the samples
189                    int fromPointer = 0;
190                    int toPointer = 0;
191                    while (!allEmpty(sortedSamples)) {
192    
193                            for (toPointer = 0; toPointer < cvSets.size(); toPointer++) {
194    
195                                    List<Sample> to = cvSets.get(toPointer);
196    
197                                    while (to.size() < (double) getSamples().getSize() / numberOfCVSets
198                                                    && fromPointer < sortedSamples.size()) {
199                                            List<Sample> from = sortedSamples.get(fromPointer);
200    
201                                            if (!from.isEmpty()) {
202                                                    to.add(from.remove(0));
203                                            }
204    
205                                            fromPointer++;
206    
207                                    }
208    
209                                    fromPointer = 0;
210    
211                            }
212    
213                    }
214    
215                    // create the data sets
216                    ClassificationDataSet train = DataSetFactory.classificationDataSet("TrainingSet "
217                                    + idOfCVSet + "/" + numberOfCVSets + "(" + randomSeed + ")");
218                    ClassificationDataSet test = DataSetFactory.classificationDataSet("TestSet " + idOfCVSet
219                                    + "/" + numberOfCVSets + "(" + randomSeed + ")");
220    
221                    test.getSamples().addAll(cvSets.remove(idOfCVSet));
222    
223                    for (List<Sample> list : cvSets) {
224                            train.getSamples().addAll(list);
225                    }
226    
227                    returnDataSets.add(train);
228                    returnDataSets.add(test);
229    
230                    return returnDataSets;
231            }
232    
233            private static boolean allEmpty(List<List<Sample>> lists) {
234                    for (List<Sample> list : lists) {
235                            if (!list.isEmpty()) {
236                                    return false;
237                            }
238                    }
239                    return true;
240            }
241    
242            public double getEarlyStoppingAccuracy(int numberOfSteps) {
243                    int index = getEarlyStoppingIndex(numberOfSteps);
244                    if (index >= 0) {
245                            return getAccuracyVariable().getMatrix(index).doubleValue();
246                    }
247                    return -1;
248            }
249    
250            public ClassificationDataSet bootstrap(int numberOfSamples) {
251                    ClassificationDataSet ds = DataSetFactory.classificationDataSet("Bootstrap of "
252                                    + getLabel());
253                    ObservableList<Sample> sampleList = getSamples();
254                    for (int i = 0; i < numberOfSamples; i++) {
255                            int rand = MathUtil.nextInteger(0, sampleList.getSize() - 1);
256                            ds.getSamples().add(sampleList.getElementAt(rand).clone());
257                    }
258                    return ds;
259            }
260    
261    }