Search in sources :

Example 1 with MLData

use of org.encog.ml.data.MLData in project shifu by ShifuML.

the class Scorer method scoreNsData.

public ScoreObject scoreNsData(MLDataPair inputPair, Map<NSColumn, String> rawNsDataMap) {
    if (inputPair == null && !this.alg.equalsIgnoreCase(NNConstants.NN_ALG_NAME)) {
        inputPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect, modelConfig, selectedColumnConfigList, rawNsDataMap, cutoff, alg);
    }
    // clear cache
    this.cachedNormDataPair.clear();
    final MLDataPair pair = inputPair;
    List<MLData> modelResults = new ArrayList<MLData>();
    List<Callable<MLData>> tasks = null;
    if (this.multiThread) {
        tasks = new ArrayList<Callable<MLData>>();
    }
    for (final BasicML model : models) {
        // TODO, check if no need 'if' condition and refactor two if for loops please
        if (model instanceof BasicFloatNetwork || model instanceof NNModel) {
            final BasicFloatNetwork network = (model instanceof BasicFloatNetwork) ? (BasicFloatNetwork) model : ((NNModel) model).getIndependentNNModel().getBasicNetworks().get(0);
            String cacheKey = featureSetToString(network.getFeatureSet());
            MLDataPair dataPair = cachedNormDataPair.get(cacheKey);
            if (dataPair == null) {
                dataPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect, modelConfig, selectedColumnConfigList, rawNsDataMap, cutoff, alg, network.getFeatureSet());
                cachedNormDataPair.put(cacheKey, dataPair);
            }
            final MLDataPair networkPair = dataPair;
            /*
                 * if(network.getFeatureSet().size() != networkPair.getInput().size()) {
                 * log.error("Network and input size mismatch: Network Size = " + network.getFeatureSet().size()
                 * + "; Input Size = " + networkPair.getInput().size());
                 * continue;
                 * }
                 */
            if (System.currentTimeMillis() % 1000 == 0L) {
                log.info("Network input count = {}, while input size = {}", network.getInputCount(), networkPair.getInput().size());
            }
            final int fnlOutputHiddenLayerIndex = outputHiddenLayerIndex;
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    MLData finalOutput = network.compute(networkPair.getInput());
                    if (fnlOutputHiddenLayerIndex == 0) {
                        return finalOutput;
                    }
                    // append output values in hidden layer
                    double[] hiddenOutputs = network.getLayerOutput(fnlOutputHiddenLayerIndex);
                    double[] outputs = new double[finalOutput.getData().length + hiddenOutputs.length];
                    System.arraycopy(finalOutput.getData(), 0, outputs, 0, finalOutput.getData().length);
                    System.arraycopy(hiddenOutputs, 0, outputs, finalOutput.getData().length, hiddenOutputs.length);
                    return new BasicMLData(outputs);
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof BasicNetwork) {
            final BasicNetwork network = (BasicNetwork) model;
            final MLDataPair networkPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect, modelConfig, columnConfigList, rawNsDataMap, cutoff, alg, null);
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    return network.compute(networkPair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof SVM) {
            final SVM svm = (SVM) model;
            if (svm.getInputCount() != pair.getInput().size()) {
                log.error("SVM and input size mismatch: SVM Size = " + svm.getInputCount() + "; Input Size = " + pair.getInput().size());
                continue;
            }
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    return svm.compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof LR) {
            final LR lr = (LR) model;
            if (lr.getInputCount() != pair.getInput().size()) {
                log.error("LR and input size mismatch: LR Size = " + lr.getInputCount() + "; Input Size = " + pair.getInput().size());
                continue;
            }
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    return lr.compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof TreeModel) {
            final TreeModel tm = (TreeModel) model;
            if (tm.getInputCount() != pair.getInput().size()) {
                throw new RuntimeException("GBDT and input size mismatch: tm input Size = " + tm.getInputCount() + "; data input Size = " + pair.getInput().size());
            }
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    MLData result = tm.compute(pair.getInput());
                    return result;
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof GenericModel) {
            Callable<MLData> callable = new Callable<MLData>() {

                @Override
                public MLData call() {
                    return ((GenericModel) model).compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else {
            throw new RuntimeException("unsupport models");
        }
    }
    List<Double> scores = new ArrayList<Double>();
    List<Integer> rfTreeSizeList = new ArrayList<Integer>();
    SortedMap<String, Double> hiddenOutputs = null;
    if (CollectionUtils.isNotEmpty(modelResults) || CollectionUtils.isNotEmpty(tasks)) {
        int modelSize = modelResults.size() > 0 ? modelResults.size() : tasks.size();
        if (modelSize != this.models.size()) {
            log.error("Get model results size doesn't match with models size.");
            return null;
        }
        if (multiThread) {
            modelResults = this.executorManager.submitTasksAndWaitResults(tasks);
        } else {
        // not multi-thread, modelResults is directly being populated in callable.call
        }
        if (this.outputHiddenLayerIndex != 0) {
            hiddenOutputs = new TreeMap<String, Double>(new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {
                    String[] split1 = o1.split("_");
                    String[] split2 = o2.split("_");
                    int model1Index = Integer.parseInt(split1[1]);
                    int model2Index = Integer.parseInt(split2[1]);
                    if (model1Index > model2Index) {
                        return 1;
                    } else if (model1Index < model2Index) {
                        return -1;
                    } else {
                        int hidden1Index = Integer.parseInt(split1[2]);
                        int hidden2Index = Integer.parseInt(split2[2]);
                        if (hidden1Index > hidden2Index) {
                            return 1;
                        } else if (hidden1Index < hidden2Index) {
                            return -1;
                        } else {
                            int hidden11Index = Integer.parseInt(split1[3]);
                            int hidden22Index = Integer.parseInt(split2[3]);
                            return Integer.valueOf(hidden11Index).compareTo(Integer.valueOf(hidden22Index));
                        }
                    }
                }
            });
        }
        for (int i = 0; i < this.models.size(); i++) {
            BasicML model = this.models.get(i);
            MLData score = modelResults.get(i);
            if (model instanceof BasicNetwork || model instanceof NNModel) {
                if (modelConfig != null && modelConfig.isRegression()) {
                    scores.add(toScore(score.getData(0)));
                    if (this.outputHiddenLayerIndex != 0) {
                        for (int j = 1; j < score.getData().length; j++) {
                            hiddenOutputs.put("model_" + i + "_" + this.outputHiddenLayerIndex + "_" + (j - 1), score.getData()[j]);
                        }
                    }
                } else if (modelConfig != null && modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll()) {
                    // if one vs all classification
                    scores.add(toScore(score.getData(0)));
                } else {
                    double[] outputs = score.getData();
                    for (double d : outputs) {
                        scores.add(toScore(d));
                    }
                }
            } else if (model instanceof SVM) {
                scores.add(toScore(score.getData(0)));
            } else if (model instanceof LR) {
                scores.add(toScore(score.getData(0)));
            } else if (model instanceof TreeModel) {
                if (modelConfig.isClassification() && !modelConfig.getTrain().isOneVsAll()) {
                    double[] scoreArray = score.getData();
                    for (double sc : scoreArray) {
                        scores.add(sc);
                    }
                } else {
                    // if one vs all multiple classification or regression
                    scores.add(toScore(score.getData(0)));
                }
                final TreeModel tm = (TreeModel) model;
                // regression for RF
                if (!tm.isClassfication() && !tm.isGBDT()) {
                    rfTreeSizeList.add(tm.getTrees().size());
                }
            } else if (model instanceof GenericModel) {
                scores.add(toScore(score.getData(0)));
            } else {
                throw new RuntimeException("unsupport models");
            }
        }
    }
    Integer tag = Constants.DEFAULT_IDEAL_VALUE;
    if (scores.size() == 0 && System.currentTimeMillis() % 100 == 0) {
        log.warn("No Scores Calculated...");
    }
    return new ScoreObject(scores, tag, rfTreeSizeList, hiddenOutputs);
}
Also used : MLDataPair(org.encog.ml.data.MLDataPair) ArrayList(java.util.ArrayList) BasicML(org.encog.ml.BasicML) SVM(org.encog.ml.svm.SVM) Callable(java.util.concurrent.Callable) Comparator(java.util.Comparator) BasicMLData(org.encog.ml.data.basic.BasicMLData) BasicFloatNetwork(ml.shifu.shifu.core.dtrain.dataset.BasicFloatNetwork) BasicMLData(org.encog.ml.data.basic.BasicMLData) MLData(org.encog.ml.data.MLData) ScoreObject(ml.shifu.shifu.container.ScoreObject) BasicNetwork(org.encog.neural.networks.BasicNetwork)

Example 2 with MLData

use of org.encog.ml.data.MLData in project shifu by ShifuML.

the class LR method compute.

@Override
public final MLData compute(final MLData input) {
    MLData result = new BasicMLData(1);
    double score = this.sigmoid(input.getData(), this.weights);
    result.setData(0, score);
    return result;
}
Also used : BasicMLData(org.encog.ml.data.basic.BasicMLData) BasicMLData(org.encog.ml.data.basic.BasicMLData) MLData(org.encog.ml.data.MLData)

Example 3 with MLData

use of org.encog.ml.data.MLData in project shifu by ShifuML.

the class AbstractTrainer method calculateMSE.

/*
     * non-synchronously version update error
     *
     * @return the standard error
     */
public static Double calculateMSE(BasicNetwork network, MLDataSet dataSet) {
    double mse = 0;
    long numRecords = dataSet.getRecordCount();
    for (int i = 0; i < numRecords; i++) {
        // Encog 3.1
        // MLDataPair pair = dataSet.get(i);
        // Encog 3.0
        double[] input = new double[dataSet.getInputSize()];
        double[] ideal = new double[1];
        MLDataPair pair = new BasicMLDataPair(new BasicMLData(input), new BasicMLData(ideal));
        dataSet.getRecord(i, pair);
        MLData result = network.compute(pair.getInput());
        double tmp = result.getData()[0] - pair.getIdeal().getData()[0];
        mse += tmp * tmp;
    }
    mse = mse / numRecords;
    return mse;
}
Also used : BasicMLDataPair(org.encog.ml.data.basic.BasicMLDataPair) MLDataPair(org.encog.ml.data.MLDataPair) BasicMLDataPair(org.encog.ml.data.basic.BasicMLDataPair) BasicMLData(org.encog.ml.data.basic.BasicMLData) BasicMLData(org.encog.ml.data.basic.BasicMLData) MLData(org.encog.ml.data.MLData)

Example 4 with MLData

use of org.encog.ml.data.MLData in project shifu by ShifuML.

the class CacheBasicFloatNetwork method compute.

/**
 * Compute network score (forward computing). If cacheInputOutput is true, to cache first layer output in this
 * class. Then if cacheInputOutput is false, read value from cache and then use sum-current item to save CPU
 * computation.
 *
 * @param input
 *            input value array
 * @param cacheInputOutput
 *            if it is to cache first layer output or to use first layer output cache.
 * @param resetInputIndex
 *            if cacheInputOutput is false, resetInputIndex is which item should be removed.
 * @return output value as score.
 */
public final MLData compute(final MLData input, boolean cacheInputOutput, int resetInputIndex) {
    try {
        final MLData result = new BasicMLData(this.network.getStructure().getFlat().getOutputCount());
        compute(input.getData(), result.getData(), cacheInputOutput, resetInputIndex);
        return result;
    } catch (final ArrayIndexOutOfBoundsException ex) {
        throw new NeuralNetworkError("Index exception: there was likely a mismatch between layer sizes, or the size of the input presented to the network.", ex);
    }
}
Also used : NeuralNetworkError(org.encog.neural.NeuralNetworkError) BasicMLData(org.encog.ml.data.basic.BasicMLData) BasicMLData(org.encog.ml.data.basic.BasicMLData) MLData(org.encog.ml.data.MLData)

Example 5 with MLData

use of org.encog.ml.data.MLData in project shifu by ShifuML.

the class GenericModel method compute.

@Override
public final MLData compute(final MLData input) {
    MLData result = new BasicMLData(1);
    if (model != null) {
        double score = model.compute(input);
        result.setData(0, score);
    }
    return result;
}
Also used : BasicMLData(org.encog.ml.data.basic.BasicMLData) BasicMLData(org.encog.ml.data.basic.BasicMLData) MLData(org.encog.ml.data.MLData)

Aggregations

MLData (org.encog.ml.data.MLData)6 BasicMLData (org.encog.ml.data.basic.BasicMLData)5 MLDataPair (org.encog.ml.data.MLDataPair)2 ArrayList (java.util.ArrayList)1 Comparator (java.util.Comparator)1 Callable (java.util.concurrent.Callable)1 ScoreObject (ml.shifu.shifu.container.ScoreObject)1 BasicFloatNetwork (ml.shifu.shifu.core.dtrain.dataset.BasicFloatNetwork)1 BasicML (org.encog.ml.BasicML)1 BasicMLDataPair (org.encog.ml.data.basic.BasicMLDataPair)1 SVM (org.encog.ml.svm.SVM)1 NeuralNetworkError (org.encog.neural.NeuralNetworkError)1 BasicNetwork (org.encog.neural.networks.BasicNetwork)1