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.libsvm;
025    
026    import libsvm.svm;
027    import libsvm.svm_model;
028    import libsvm.svm_node;
029    import libsvm.svm_parameter;
030    import libsvm.svm_problem;
031    
032    import org.jdmp.core.algorithm.classification.AbstractClassifier;
033    import org.jdmp.core.algorithm.classification.Classifier;
034    import org.jdmp.core.dataset.RegressionDataSet;
035    import org.jdmp.core.sample.ClassificationSample;
036    import org.ujmp.core.Matrix;
037    import org.ujmp.core.MatrixFactory;
038    import org.ujmp.core.exceptions.MatrixException;
039    
040    public class SVMClassifier extends AbstractClassifier {
041            private static final long serialVersionUID = -3809157647628200950L;
042    
043            private svm_parameter param = null;
044    
045            private svm_problem prob = null; // set by read_problem
046    
047            private svm_model model = null;
048    
049            private Kernel kernel = null;
050    
051            public enum Kernel {
052                    LINEAR, RBF, SIGMOID, POLYNOM
053            };
054    
055            public SVMClassifier() {
056                    this(Kernel.RBF);
057            }
058    
059            public SVMClassifier(Kernel kernel) {
060                    super();
061                    setLabel("SVM " + kernel.name());
062                    this.kernel = kernel;
063                    createAlgorithm();
064            }
065    
066            private void createAlgorithm() {
067                    param = new svm_parameter();
068    
069                    param.svm_type = svm_parameter.C_SVC;
070    
071                    switch (kernel) {
072                    case LINEAR:
073                            param.kernel_type = svm_parameter.LINEAR;
074                            break;
075                    case SIGMOID:
076                            param.kernel_type = svm_parameter.SIGMOID;
077                            break;
078                    case POLYNOM:
079                            param.kernel_type = svm_parameter.POLY;
080                            break;
081                    case RBF:
082                            param.kernel_type = svm_parameter.RBF;
083                            break;
084                    }
085    
086                    param.degree = 3;
087                    param.gamma = 0; // 1/k
088                    param.coef0 = 0;
089                    param.nu = 0.5;
090                    param.cache_size = 100;
091                    param.C = 1;
092                    param.eps = 1e-3;
093                    param.p = 0.1;
094                    param.shrinking = 1;
095                    param.probability = 1;
096                    param.nr_weight = 0;
097                    param.weight_label = new int[0];
098                    param.weight = new double[0];
099            }
100    
101            @Override
102            public void train(RegressionDataSet dataSet) throws MatrixException {
103                    int columnCount = (int) dataSet.getSamples().getElementAt(0).getMatrix(INPUT)
104                                    .getColumnCount();
105    
106                    prob = new svm_problem();
107                    prob.l = dataSet.getSamples().getSize();
108    
109                    prob.x = new svm_node[prob.l][columnCount];
110                    prob.y = new double[prob.l];
111    
112                    for (int i = 0; i < prob.l; i++) {
113                            ClassificationSample p = (ClassificationSample) dataSet.getSamples().getElementAt(i);
114                            Matrix input = p.getMatrix(INPUT);
115                            prob.y[i] = p.getTargetClass();
116                            for (int j = 0; j < columnCount; j++) {
117                                    prob.x[i][j] = new svm_node();
118                                    prob.x[i][j].index = j + 1;
119                                    prob.x[i][j].value = input.getAsDouble(0, j);
120                            }
121                    }
122    
123                    if (param.gamma == 0)
124                            param.gamma = 1.0 / columnCount;
125    
126                    if (param.kernel_type == svm_parameter.PRECOMPUTED)
127                            for (int i = 0; i < prob.l; i++) {
128                                    if (prob.x[i][0].index != 0) {
129                                            System.err
130                                                            .print("Wrong kernel matrix: first column must be 0:sample_serial_number\n");
131                                            System.exit(1);
132                                    }
133                                    if ((int) prob.x[i][0].value <= 0 || (int) prob.x[i][0].value > columnCount) {
134                                            System.err.print("Wrong input format: sample_serial_number out of range\n");
135                                            System.exit(1);
136                                    }
137                            }
138    
139                    String error_msg = svm.svm_check_parameter(prob, param);
140    
141                    if (error_msg != null) {
142                            System.err.print("Error: " + error_msg + "\n");
143                    } else {
144                            model = svm.svm_train(prob, param);
145                    }
146            }
147    
148            @Override
149            public Matrix predict(Matrix input, Matrix weight) throws MatrixException {
150                    int nr_class = svm.svm_get_nr_class(model);
151                    double[] prob_estimates = new double[nr_class];
152    
153                    int m = (int) input.getColumnCount();
154                    svm_node[] x = new svm_node[m];
155                    for (int j = 0; j < m; j++) {
156                            x[j] = new svm_node();
157                            x[j].index = j + 1;
158                            x[j].value = input.getAsDouble(0, j);
159                    }
160    
161                    svm.svm_predict_probability(model, x, prob_estimates);
162                    Matrix output = MatrixFactory.zeros(1, svm.svm_get_nr_class(model));
163                    int[] label = new int[svm.svm_get_nr_class(model)];
164                    svm.svm_get_labels(model, label);
165    
166                    for (int i = 0; i < label.length; i++) {
167                            output.setAsDouble(prob_estimates[i], 0, label[i]);
168                    }
169    
170                    return output;
171            }
172    
173            @Override
174            public void train(Matrix input, Matrix sampleWeight, Matrix targetOutput) throws Exception {
175                    throw new Exception("not supported");
176            }
177    
178            @Override
179            public void reset() throws MatrixException {
180                    createAlgorithm();
181            }
182    
183            public Classifier emptyCopy() {
184                    return new SVMClassifier(kernel);
185            }
186    
187    }