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.mlp;
025    
026    import java.util.ArrayList;
027    import java.util.Collections;
028    import java.util.List;
029    
030    import org.jdmp.core.algorithm.AlgorithmTwoSources;
031    import org.jdmp.core.algorithm.classification.AbstractClassifier;
032    import org.jdmp.core.algorithm.classification.Classifier;
033    import org.jdmp.core.dataset.ClassificationDataSet;
034    import org.jdmp.core.dataset.RegressionDataSet;
035    import org.jdmp.core.sample.Sample;
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.coordinates.Coordinates;
041    import org.ujmp.core.exceptions.MatrixException;
042    import org.ujmp.core.listmatrix.DefaultListMatrix;
043    
044    public class MultiLayerNetwork extends AbstractClassifier {
045            private static final long serialVersionUID = -6875411556504865444L;
046    
047            private Aggregation aggregationInput = null;
048    
049            private Transfer transferInput = null;
050    
051            private BiasType biasInput = null;
052    
053            private Aggregation aggregationDefault = null;
054    
055            private Transfer transferDefault = null;
056    
057            private BiasType biasDefault = null;
058    
059            private Aggregation aggregationOutput = null;
060    
061            private Transfer transferOutput = null;
062    
063            private BiasType biasOutput = null;
064    
065            private int[] neuronCount = null;
066    
067            public enum Aggregation {
068                    MEAN, SUM
069            };
070    
071            public enum Transfer {
072                    TANH, TANHPLUSONE, SIGMOID, LINEAR, SIN, LOG, GAUSS
073            };
074    
075            public enum BiasType {
076                    NONE, SINGLE, MULTIPLE
077            };
078    
079            private final List<NetworkLayer> networkLayers = new ArrayList<NetworkLayer>();
080    
081            public MultiLayerNetwork(Aggregation aggregationInput, Transfer transferInput,
082                            BiasType biasInput, Aggregation aggregationDefault, Transfer transferDefault,
083                            BiasType biasDefault, Aggregation aggregationOutput, Transfer transferOutput,
084                            BiasType biasOutput, int... hiddenNeurons) {
085                    super();
086    
087                    this.aggregationInput = aggregationInput;
088                    this.transferInput = transferInput;
089                    this.biasInput = biasInput;
090                    this.aggregationDefault = aggregationDefault;
091                    this.transferDefault = transferDefault;
092                    this.biasDefault = biasDefault;
093                    this.aggregationOutput = aggregationOutput;
094                    this.transferOutput = transferOutput;
095                    this.biasOutput = biasOutput;
096                    this.neuronCount = hiddenNeurons;
097    
098                    NetworkLayer previousLayer = null;
099                    if (hiddenNeurons != null) {
100                            NetworkLayer hiddenLayer = null;
101                            for (int i = 0; i < hiddenNeurons.length; i++) {
102                                    if (i == 0) {
103                                            hiddenLayer = new NetworkLayer(aggregationInput, transferInput, biasInput,
104                                                            hiddenNeurons[i]);
105                                    } else {
106                                            hiddenLayer = new NetworkLayer(aggregationDefault, transferDefault,
107                                                            biasDefault, hiddenNeurons[i]);
108                                    }
109                                    getAlgorithms().put("hidden" + i + "-forward", hiddenLayer.getAlgorithmForward());
110                                    getAlgorithms().put("hidden" + i + "-backward", hiddenLayer.getAlgorithmBackward());
111                                    getAlgorithms().put("hidden" + i + "-update",
112                                                    hiddenLayer.getAlgorithmWeightUpdate());
113                                    hiddenLayer.setLayer(i);
114                                    networkLayers.add(hiddenLayer);
115                                    if (previousLayer != null) {
116                                            previousLayer.setNextLayer(hiddenLayer);
117                                    }
118                                    hiddenLayer.setPreviousLayer(previousLayer);
119                                    previousLayer = hiddenLayer;
120                            }
121                    }
122    
123                    NetworkLayer outputLayer = new NetworkLayer(aggregationOutput, transferOutput, biasOutput);
124                    getAlgorithms().put("output" + "-forward", outputLayer.getAlgorithmForward());
125                    getAlgorithms().put("output" + "-backward", outputLayer.getAlgorithmBackward());
126                    getAlgorithms().put("output" + "-update", outputLayer.getAlgorithmWeightUpdate());
127                    outputLayer.setLayer(hiddenNeurons.length);
128                    networkLayers.add(outputLayer);
129                    if (previousLayer != null) {
130                            previousLayer.setNextLayer(outputLayer);
131                            outputLayer.setPreviousLayer(previousLayer);
132                    }
133    
134                    Variable output = VariableFactory.labeledVariable("Output");
135                    setOutputVariable(output);
136    
137                    Variable outputDeviation = VariableFactory.labeledVariable("Output Deviation");
138                    setOutputDeviationVariable(outputDeviation);
139    
140                    Variable input = VariableFactory.labeledVariable("Input");
141                    setInputVariable(input);
142    
143                    Variable desiredOutput = VariableFactory.labeledVariable("Desired Output");
144                    setDesiredOutputVariable(desiredOutput);
145            }
146    
147            public MultiLayerNetwork(int... neuronCount) {
148                    this(Aggregation.SUM, Transfer.TANH, BiasType.SINGLE, Aggregation.SUM, Transfer.TANH,
149                                    BiasType.SINGLE, Aggregation.SUM, Transfer.TANH, BiasType.SINGLE, neuronCount);
150            }
151    
152            public MultiLayerNetwork(Aggregation aggregation, Transfer transfer, int... neuronCount) {
153                    this(aggregation, transfer, BiasType.SINGLE, aggregation, transfer, BiasType.SINGLE,
154                                    aggregation, transfer, BiasType.SINGLE, neuronCount);
155            }
156    
157            public MultiLayerNetwork(Aggregation aggregation, BiasType bias, int... neuronCount) {
158                    this(aggregation, Transfer.TANH, bias, aggregation, Transfer.TANH, bias, aggregation,
159                                    Transfer.TANH, bias, neuronCount);
160            }
161    
162            public MultiLayerNetwork(Aggregation aggregation, int... neuronCount) {
163                    this(aggregation, Transfer.TANH, BiasType.SINGLE, aggregation, Transfer.TANH,
164                                    BiasType.SINGLE, aggregation, Transfer.TANH, BiasType.SINGLE, neuronCount);
165            }
166    
167            public MultiLayerNetwork(Aggregation aggregation, Transfer transfer, BiasType biasType,
168                            int... neurons) {
169                    this(aggregation, transfer, biasType, aggregation, transfer, biasType, aggregation,
170                                    transfer, biasType, neurons);
171            }
172    
173            public void setOutputVariable(Variable v) {
174                    getOutputErrorAlgorithm().setVariable(AlgorithmTwoSources.SOURCE1, v);
175                    getOutputLayer().setOutputVariable(v);
176            }
177    
178            public void setOutputDeviationVariable(Variable v) {
179                    getOutputErrorAlgorithm().setVariable(AlgorithmTwoSources.TARGET, v);
180                    getOutputLayer().setOutputDeviationVariable(v);
181            }
182    
183            public void setLearningRate(double v) {
184                    for (NetworkLayer networkLayer : networkLayers) {
185                            networkLayer.setLearningRate(v);
186                    }
187            }
188    
189            public double getLearningRate() {
190                    return networkLayers.get(0).getLearningRate();
191            }
192    
193            @Override
194            public void reset() throws MatrixException {
195                    for (NetworkLayer networkLayer : networkLayers) {
196                            networkLayer.reset();
197                    }
198            }
199    
200            public NetworkLayer getOutputLayer() {
201                    return networkLayers.get(networkLayers.size() - 1);
202            }
203    
204            public NetworkLayer getInputLayer() {
205                    return networkLayers.get(0);
206            }
207    
208            public Variable getInputVariable() {
209                    return getInputLayer().getInputVariable();
210            }
211    
212            public void setInputVariable(Variable v) {
213                    getInputLayer().setInputVariable(v);
214            }
215    
216            public void setDesiredOutputVariable(Variable v) {
217                    getOutputErrorAlgorithm().setVariable(AlgorithmTwoSources.SOURCE2, v);
218                    getOutputLayer().getOutputVariable().setSize(v.getRowCount(), v.getColumnCount());
219                    getOutputLayer().getOutputDeviationVariable().setSize(v.getRowCount(), v.getColumnCount());
220            }
221    
222            public void addInputMatrix(Matrix m) {
223                    getInputLayer().addInputMatrix(m);
224            }
225    
226            public void setSampleWeight(double weight) {
227                    for (NetworkLayer networkLayer : networkLayers) {
228                            networkLayer.setSampleWeight(weight);
229                    }
230            }
231    
232            public void addDesiredOutputMatrix(Matrix m) {
233                    getOutputErrorAlgorithm().setMatrix(AlgorithmTwoSources.SOURCE2, m);
234                    if (Coordinates.product(getOutputVariable().getSize()) == 0) {
235                            getOutputVariable().setSize(m.getRowCount(), m.getColumnCount());
236                    }
237                    if (Coordinates.product(getOutputDeviationVariable().getSize()) == 0) {
238                            getOutputDeviationVariable().setSize(m.getRowCount(), m.getColumnCount());
239                    }
240            }
241    
242            public Variable getOutputVariable() {
243                    return getOutputLayer().getOutputVariable();
244            }
245    
246            public Variable getOutputDeviationVariable() {
247                    return getOutputLayer().getOutputDeviationVariable();
248            }
249    
250            public List<NetworkLayer> getNetworkLayerList() {
251                    return networkLayers;
252            }
253    
254            @Override
255            public Matrix predict(Matrix input, Matrix sampleWeight) throws Exception {
256                    // transpose and add bias unit
257                    // Matrix inputWithBias = Matrix.zeros(input.getColumnCount() + 1,
258                    // input.getRowCount());
259                    // for (long i = input.getColumnCount() - 1; i != -1; i--) {
260                    // inputWithBias.setDouble(input.getDouble(0, i), i, 0);
261                    // }
262                    // inputWithBias.setDouble(1.0, inputWithBias.getRowCount() - 1, 0);
263                    addInputMatrix(input);
264    
265                    for (NetworkLayer networkLayer : getNetworkLayerList()) {
266                            networkLayer.calculateForward();
267                    }
268    
269                    Matrix actualOutput = getOutputMatrix().transpose();
270                    return actualOutput;
271            }
272    
273            public Matrix getOutputMatrix() {
274                    return getOutputVariable().getMatrix();
275            }
276    
277            @Override
278            public void train(Matrix input, Matrix sampleWeight, Matrix desiredOutput) throws Exception {
279                    addDesiredOutputMatrix(desiredOutput.toRowVector());
280                    if (sampleWeight == null) {
281                            sampleWeight = MatrixFactory.linkToValue(1.0);
282                    }
283                    setSampleWeight(sampleWeight.doubleValue());
284                    predict(input, sampleWeight);
285                    getOutputErrorAlgorithm().calculate();
286    
287                    for (int i = networkLayers.size() - 1; i != -1; i--) {
288                            networkLayers.get(i).calculateBackward();
289                    }
290    
291                    for (int i = networkLayers.size() - 1; i != -1; i--) {
292                            networkLayers.get(i).calculateWeightUpdate();
293                    }
294    
295            }
296    
297            public int determineOptimalTrainingDuration(ClassificationDataSet dataSet, int numberOfSteps)
298                            throws Exception {
299                    long seed = System.currentTimeMillis();
300                    DefaultListMatrix<Double> duration = new DefaultListMatrix<Double>();
301                    for (int r = 0; r < 10; r++) {
302                            List<ClassificationDataSet> dss = dataSet.splitForStratifiedCV(10, r, seed);
303                            ClassificationDataSet train = dss.get(0);
304                            ClassificationDataSet test = dss.get(1);
305                            MultiLayerNetwork a = new MultiLayerNetwork(aggregationInput, transferInput, biasInput,
306                                            aggregationDefault, transferDefault, biasDefault, aggregationOutput,
307                                            transferOutput, biasOutput, neuronCount);
308                            a.setLearningRate(getLearningRate());
309                            for (int i = 0; i < 10000; i++) {
310                                    a.train(train);
311                                    a.predict(test);
312                                    // System.out.println(i+": "+test.getRMSE());
313                                    if (test.isEarlyStoppingReached(numberOfSteps)) {
314                                            double d = test.getEarlyStoppingIndex(numberOfSteps);
315                                            duration.add(d);
316                                            // System.out.println("CV"+r+": "+d);
317                                            break;
318                                    }
319                            }
320                    }
321                    int mean = (int) (duration.getMeanValue() * 0.9);
322                    // System.out.println("Optimal: "+mean);
323                    if (mean == 0) {
324                            mean = 1;
325                    }
326                    return mean;
327            }
328    
329            @Override
330            public void train(RegressionDataSet dataSet) throws Exception {
331    
332                    // TODO: fix!
333    
334                    List<Sample> samples = new ArrayList<Sample>(dataSet.getSamples().toCollection());
335                    Collections.shuffle(samples);
336    
337                    int last10Percent = (int) Math.ceil((samples.size() * 0.1));
338                    int first90Percent = samples.size() - last10Percent;
339    
340                    for (int i = 0; i < first90Percent; i++) {
341                            train(samples.get(i));
342                    }
343    
344                    // Crossvalidation
345                    double rmse = 0;
346                    for (int i = first90Percent; i < samples.size(); i++) {
347                            Sample rs = samples.get(i);
348                            Matrix output = predict(rs.getMatrix(INPUT), rs.getMatrix(WEIGHT));
349                            rmse += output.minus(rs.getMatrix(TARGET)).getRMS();
350                            train(samples.get(i));
351                    }
352                    rmse /= last10Percent;
353    
354                    System.out.println("RMSE on " + last10Percent + " Samples: " + rmse);
355    
356                    for (int i = first90Percent; i < samples.size(); i++) {
357                            train(samples.get(i));
358                    }
359            }
360    
361            public void trainOnce(RegressionDataSet dataSet) throws Exception {
362                    List<Sample> samples = new ArrayList<Sample>(dataSet.getSamples().toCollection());
363                    Collections.shuffle(samples);
364                    for (Sample s : samples) {
365                            train(s);
366                    }
367                    dataSet.notifyGUIObject();
368            }
369    
370            @Override
371            public Classifier emptyCopy() throws Exception {
372                    return null;
373            }
374    
375    }