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.liblinear;
025    
026    import liblinear.FeatureNode;
027    import liblinear.Linear;
028    import liblinear.Model;
029    import liblinear.Parameter;
030    import liblinear.Problem;
031    import liblinear.SolverType;
032    
033    import org.jdmp.core.algorithm.classification.AbstractClassifier;
034    import org.jdmp.core.algorithm.classification.Classifier;
035    import org.jdmp.core.dataset.RegressionDataSet;
036    import org.jdmp.core.sample.ClassificationSample;
037    import org.ujmp.core.Matrix;
038    import org.ujmp.core.MatrixFactory;
039    import org.ujmp.core.exceptions.MatrixException;
040    import org.ujmp.core.util.MathUtil;
041    
042    public class LibLinearClassifier extends AbstractClassifier {
043            private static final long serialVersionUID = 895205125219258509L;
044    
045            private Parameter param = null;
046    
047            private Problem prob = null;
048    
049            private Model model = null;
050    
051            private final double bias = 1.0;
052    
053            @Override
054            public Matrix predict(Matrix input, Matrix sampleWeight) throws Exception {
055                    long columnCount = input.getColumnCount();
056                    int count = 0;
057                    for (int j = 0; j < columnCount; j++) {
058                            double value = input.getAsDouble(0, j);
059                            if (value != 0.0 && !MathUtil.isNaNOrInfinite(value)) {
060                                    count++;
061                            }
062                    }
063                    // +1 to include bias
064                    FeatureNode[] x = new FeatureNode[count + 1];
065                    x[0] = new FeatureNode(1, bias);
066                    count = 0;
067                    for (int j = 0; j < columnCount; j++) {
068                            double value = input.getAsDouble(0, j);
069                            if (value != 0.0 && !MathUtil.isNaNOrInfinite(value)) {
070                                    x[count + 1] = new FeatureNode(count + 2, value);
071                                    count++;
072                            }
073                    }
074    
075                    int classId = Linear.predict(model, x);
076                    Matrix ret = MatrixFactory.zeros(1, model.getNrClass());
077                    ret.setAsDouble(1.0, 0, classId);
078                    return ret;
079            }
080    
081            @Override
082            public void train(RegressionDataSet dataSet) throws Exception {
083                    createAlgorithm();
084                    prob = new Problem();
085                    prob.l = dataSet.getSamples().getSize();
086                    prob.n = (int) dataSet.getSamples().getElementAt(0).getMatrix(INPUT)
087                                    .getColumnCount() + 1; // +1 for bias
088    
089                    prob.x = new FeatureNode[prob.l][];
090                    prob.y = new int[prob.l];
091    
092                    // calculate weights
093                    // double[] targetCounts = dataSet.getTargetMatrix().sum(Ret.NEW,
094                    // Matrix.ROW, true).toDoubleArray()[0];
095                    // double[] weights = new double[targetCounts.length];
096                    // int[] weightLabels = new int[targetCounts.length];
097                    // for (int i = 0; i < targetCounts.length; i++) {
098                    // weights[i] = 1 - targetCounts[i] / prob.l;
099                    // weightLabels[i] = i;
100                    // }
101                    // param.setWeights(weights, weightLabels);
102    
103                    for (int i = 0; i < prob.l; i++) {
104                            if (i % 10 == 0) {
105                                    System.out.println("Converting sample " + i);
106                            }
107                            ClassificationSample p = (ClassificationSample) dataSet
108                                            .getSamples().getElementAt(i);
109                            Matrix input = p.getMatrix(INPUT);
110                            prob.y[i] = p.getTargetClass();
111                            long columnCount = input.getColumnCount();
112                            int count = 0;
113                            for (int j = 0; j < columnCount; j++) {
114                                    double value = input.getAsDouble(0, j);
115                                    if (value != 0.0 && !MathUtil.isNaNOrInfinite(value)) {
116                                            count++;
117                                    }
118                            }
119                            // +1 to include bias
120                            prob.x[i] = new FeatureNode[count + 1];
121                            prob.x[i][0] = new FeatureNode(1, bias);
122                            count = 0;
123                            for (int j = 0; j < columnCount; j++) {
124                                    double value = input.getAsDouble(0, j);
125                                    if (value != 0.0 && !MathUtil.isNaNOrInfinite(value)) {
126                                            prob.x[i][count + 1] = new FeatureNode(count + 2, value);
127                                            count++;
128                                    }
129                            }
130                    }
131                    model = Linear.train(prob, param);
132            }
133    
134            @Override
135            public void train(Matrix input, Matrix sampleWeight, Matrix targetOutput)
136                            throws Exception {
137                    throw new Exception("not supported");
138            }
139    
140            public Classifier emptyCopy() throws Exception {
141                    return new LibLinearClassifier();
142            }
143    
144            private void createAlgorithm() {
145                    model = null;
146                    prob = null;
147                    // param = new Parameter(SolverType.L2LOSS_SVM_DUAL, 1,
148                    // Double.POSITIVE_INFINITY);
149                    param = new Parameter(SolverType.L2LOSS_SVM_DUAL, 1, 0.1);
150    
151            }
152    
153            @Override
154            public void reset() throws MatrixException {
155                    createAlgorithm();
156            }
157    
158    }