Example usage for org.apache.commons.math3.util Pair getSecond

List of usage examples for org.apache.commons.math3.util Pair getSecond

Introduction

In this page you can find the example usage for org.apache.commons.math3.util Pair getSecond.

Prototype

public V getSecond() 

Source Link

Document

Get the second element of the pair.

Usage

From source file:com.cloudera.oryx.als.serving.web.RecommendToAnonymousServlet.java

static Pair<String[], float[]> parseItemValuePairs(Iterator<String> pathComponents) {
    List<Pair<String, Float>> itemValuePairs = Lists.newArrayListWithCapacity(1);
    while (pathComponents.hasNext()) {
        itemValuePairs.add(parseItemValue(pathComponents.next()));
    }/*from   w  w w  .  jav a2 s.  co m*/

    int size = itemValuePairs.size();
    String[] itemIDs = new String[size];
    float[] values = new float[size];
    for (int i = 0; i < size; i++) {
        Pair<String, Float> itemValuePair = itemValuePairs.get(i);
        itemIDs[i] = itemValuePair.getFirst();
        Float value = itemValuePair.getSecond();
        values[i] = value == null ? 1.0f : value;
    }

    return new Pair<String[], float[]>(itemIDs, values);
}

From source file:net.myrrix.web.servlets.RecommendToAnonymousServlet.java

static Pair<long[], float[]> parseItemValuePairs(Iterator<String> pathComponents) {
    List<Pair<Long, Float>> itemValuePairs = Lists.newArrayListWithCapacity(1);
    while (pathComponents.hasNext()) {
        itemValuePairs.add(parseItemValue(pathComponents.next()));
    }//from   www .j  a v  a  2s.co  m

    int size = itemValuePairs.size();
    long[] itemIDs = new long[size];
    float[] values = new float[size];
    for (int i = 0; i < size; i++) {
        Pair<Long, Float> itemValuePair = itemValuePairs.get(i);
        itemIDs[i] = itemValuePair.getFirst();
        Float value = itemValuePair.getSecond();
        values[i] = value == null ? 1.0f : value;
    }

    return new Pair<long[], float[]>(itemIDs, values);
}

From source file:com.insightml.utils.ui.UiUtils.java

public static String format(final PairList<?, ?> list) {
    final StringBuilder builder = new StringBuilder();
    if (list == null) {
        return null;
    }/*from w  ww . j a  va  2 s . c  om*/
    for (final Pair<?, ?> entry : list) {
        builder.append(fill(format(entry.getFirst()), 45) + " ");
        builder.append(format(entry.getSecond()));
        builder.append('\n');
    }
    return builder.toString();
}

From source file:com.insightml.AbstractModelTest.java

private static void test(final Pair<? extends ILearner, Double> tuple,
        final IDataset<SimpleSample, Double, ?> instances,
        final ObjectiveFunction<? super SimpleSample, ? super Serializable> objective) {
    if (tuple != null) {
        final double expected = tuple.getSecond();
        Assert.assertTrue(expected + " > -0.82", expected > -0.82);
        Tests.testLearner(tuple.getFirst(), instances, objective, expected);
    }//from   w  w w  . j a v a2 s  .c  om
}

From source file:com.insightml.utils.Collections.java

public static <T, N extends Number> LinkedList<Pair<T, N>> getMax(final Iterable<Pair<T, N>> map) {
    LinkedList<Pair<T, N>> maxEntry = new LinkedList<>();
    for (final Pair<T, N> entry : map) {
        if (maxEntry.size() == 0
                || entry.getSecond().doubleValue() > maxEntry.getFirst().getSecond().doubleValue()) {
            maxEntry = new LinkedList<>();
            maxEntry.add(entry);//from w  w w.  j  a  va  2s. c  om
        } else if (entry.getSecond().doubleValue() == maxEntry.getFirst().getSecond().doubleValue()) {
            maxEntry.add(entry);
        }
    }
    return maxEntry;
}

From source file:com.insightml.utils.io.IoUtils.java

public static void zip2(final List<Pair<InputStream, String>> files, final File target) {
    final byte[] buffer = new byte[1024];
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target))) {
        for (final Pair<InputStream, String> file : files) {
            final ZipEntry ze = new ZipEntry(file.getSecond());
            zos.putNextEntry(ze);/*from  w  w  w.  j a  va2 s .co  m*/

            int len;
            while ((len = file.getFirst().read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            file.getFirst().close();
            zos.closeEntry();
        }
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.cloudera.oryx.rdf.common.tree.DecisionTree.java

private static TreeNode build(ExampleSet examples, int buildAtDepth, int minNodeSize, double minInfoGainNats,
        int featuresToTry, int numFeatures, int suggestedMaxSplitCandidates, int maxDepth,
        RandomGenerator random) {/*w w w.  j  a  v a 2s.c om*/
    if (buildAtDepth >= maxDepth - 1 || examples.getExamples().size() < minNodeSize) {
        return new TerminalNode(Prediction.buildPrediction(examples));
    }

    double bestGain = Double.NEGATIVE_INFINITY;
    Decision bestDecision = null;

    for (int featureNumber : randomFeatures(examples, featuresToTry, numFeatures, random)) {
        Iterable<Decision> decisions = Decision.decisionsFromExamples(examples, featureNumber,
                suggestedMaxSplitCandidates);
        Pair<Decision, Double> decisionAndGain = Information.bestGain(decisions, examples);
        if (decisionAndGain != null) {
            double gain = decisionAndGain.getSecond();
            if (gain > bestGain) {
                bestGain = gain;
                bestDecision = decisionAndGain.getFirst();
            }
        }
    }

    if (Double.isNaN(bestGain) || bestGain < minInfoGainNats) {
        return new TerminalNode(Prediction.buildPrediction(examples));
    }

    bestDecision.setInformationGain(bestGain);

    ExampleSet[] negPosSplit = examples.split(bestDecision);
    examples = null; // For GC?

    TreeNode left = build(negPosSplit[0], buildAtDepth + 1, minNodeSize, minInfoGainNats, featuresToTry,
            numFeatures, suggestedMaxSplitCandidates, maxDepth, random);
    TreeNode right = build(negPosSplit[1], buildAtDepth + 1, minNodeSize, minInfoGainNats, featuresToTry,
            numFeatures, suggestedMaxSplitCandidates, maxDepth, random);

    return new DecisionNode(bestDecision, left, right);
}

From source file:it.unibo.alchemist.language.protelis.util.ReflectionUtils.java

private static Method loadBestMethod(final Class<?> clazz, final String methodName, final Class<?>[] argClass) {
    Objects.requireNonNull(clazz, "The class on which the method will be invoked can not be null.");
    Objects.requireNonNull(methodName, "Method name can not be null.");
    Objects.requireNonNull(argClass, "Method arguments can not be null.");
    /*//  ww  w  .j ava2s  . co  m
     * If there is a matching method, return it
     */
    try {
        return clazz.getMethod(methodName, argClass);
    } catch (NoSuchMethodException | SecurityException e) {
        /*
         * Look it up on the cache
         */
        /*
         * Deal with Java method overloading scoring methods
         */
        final Method[] candidates = clazz.getMethods();
        final List<Pair<Integer, Method>> lm = new ArrayList<>(candidates.length);
        for (final Method m : candidates) {
            // TODO: Workaround for different Method API
            if (m.getParameterTypes().length == argClass.length && methodName.equals(m.getName())) {
                final Class<?>[] params = m.getParameterTypes();
                int p = 0;
                boolean compatible = true;
                for (int i = 0; compatible && i < argClass.length; i++) {
                    final Class<?> expected = params[i];
                    if (expected.isAssignableFrom(argClass[i])) {
                        /*
                         * No downcast required, there is compatibility
                         */
                        p++;
                    } else if (!PrimitiveUtils.classIsNumber(expected)) {
                        compatible = false;
                    }
                }
                if (compatible) {
                    lm.add(new Pair<>(p, m));
                }
            }
        }
        /*
         * Find best
         */
        if (lm.size() > 0) {
            Pair<Integer, Method> max = lm.get(0);
            for (Pair<Integer, Method> cPair : lm) {
                if (cPair.getFirst().compareTo(max.getFirst()) > 0) {
                    max = cPair;
                }
            }
            return max.getSecond();
        }
    }
    List<Class<?>> list = new ArrayList<>();
    for (Class<?> c : argClass) {
        list.add(c);
    }
    final String argType = list.toString();
    throw new NoSuchMethodError(
            methodName + "/" + argClass.length + argType + " does not exist in " + clazz + ".");
}

From source file:com.cloudera.oryx.rdf.common.pmml.DecisionForestPMML.java

private static Segment buildTreeModel(DecisionForest forest,
        Map<Integer, BiMap<String, Integer>> columnToCategoryNameToIDMapping,
        MiningFunctionType miningFunctionType, MiningSchema miningSchema, int treeID, DecisionTree tree,
        InboundSettings settings) {/*from ww  w .j  av  a  2 s  . c o m*/

    List<String> columnNames = settings.getColumnNames();
    int targetColumn = settings.getTargetColumn();

    Node root = new Node();
    root.setId("r");

    // Queue<Node> modelNodes = Queues.newArrayDeque();
    Queue<Node> modelNodes = new ArrayDeque<Node>();
    modelNodes.add(root);

    Queue<Pair<TreeNode, Decision>> treeNodes = new ArrayDeque<Pair<TreeNode, Decision>>();
    treeNodes.add(new Pair<TreeNode, Decision>(tree.getRoot(), null));

    while (!treeNodes.isEmpty()) {

        Pair<TreeNode, Decision> treeNodePredicate = treeNodes.remove();
        Node modelNode = modelNodes.remove();

        // This is the decision that got us here from the parent, if any; not the predicate at this node
        Predicate predicate = buildPredicate(treeNodePredicate.getSecond(), columnNames,
                columnToCategoryNameToIDMapping);
        modelNode.setPredicate(predicate);

        TreeNode treeNode = treeNodePredicate.getFirst();
        if (treeNode.isTerminal()) {

            TerminalNode terminalNode = (TerminalNode) treeNode;
            modelNode.setRecordCount((double) terminalNode.getCount());

            Prediction prediction = terminalNode.getPrediction();

            if (prediction.getFeatureType() == FeatureType.CATEGORICAL) {

                Map<Integer, String> categoryIDToName = columnToCategoryNameToIDMapping.get(targetColumn)
                        .inverse();
                CategoricalPrediction categoricalPrediction = (CategoricalPrediction) prediction;
                int[] categoryCounts = categoricalPrediction.getCategoryCounts();
                float[] categoryProbabilities = categoricalPrediction.getCategoryProbabilities();
                for (int categoryID = 0; categoryID < categoryProbabilities.length; categoryID++) {
                    int categoryCount = categoryCounts[categoryID];
                    float probability = categoryProbabilities[categoryID];
                    if (categoryCount > 0 && probability > 0.0f) {
                        String categoryName = categoryIDToName.get(categoryID);
                        ScoreDistribution distribution = new ScoreDistribution(categoryName, categoryCount);
                        distribution.setProbability((double) probability);
                        modelNode.getScoreDistributions().add(distribution);
                    }
                }

            } else {

                NumericPrediction numericPrediction = (NumericPrediction) prediction;
                modelNode.setScore(Float.toString(numericPrediction.getPrediction()));
            }

        } else {

            DecisionNode decisionNode = (DecisionNode) treeNode;
            Decision decision = decisionNode.getDecision();

            Node positiveModelNode = new Node();
            positiveModelNode.setId(modelNode.getId() + '+');
            modelNode.getNodes().add(positiveModelNode);
            Node negativeModelNode = new Node();
            negativeModelNode.setId(modelNode.getId() + '-');
            modelNode.getNodes().add(negativeModelNode);
            modelNode.setDefaultChild(
                    decision.getDefaultDecision() ? positiveModelNode.getId() : negativeModelNode.getId());
            modelNodes.add(positiveModelNode);
            modelNodes.add(negativeModelNode);
            treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getRight(), decision));
            treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getLeft(), null));

        }

    }

    TreeModel treeModel = new TreeModel(miningSchema, root, miningFunctionType);
    treeModel.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);
    treeModel.setMissingValueStrategy(MissingValueStrategyType.DEFAULT_CHILD);

    Segment segment = new Segment();
    segment.setId(Integer.toString(treeID));
    segment.setPredicate(new True());
    segment.setModel(treeModel);
    segment.setWeight(forest.getWeights()[treeID]);

    return segment;
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

private static <I, O> Pair<O, O> mapPair(final Pair<? extends I, ? extends I> pair,
        final Function<? super I, ? extends O> converter) {
    return new Pair<>(converter.apply(pair.getFirst()), converter.apply(pair.getSecond()));
}