Example usage for com.google.common.collect Ordering usingToString

List of usage examples for com.google.common.collect Ordering usingToString

Introduction

In this page you can find the example usage for com.google.common.collect Ordering usingToString.

Prototype

@GwtCompatible(serializable = true)
public static Ordering<Object> usingToString() 

Source Link

Document

Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString() .

Usage

From source file:com.tdunning.ch16.train.TrainNewsGroups.java

public static void main(String[] args) throws IOException {
    File base = new File(args[0]);

    int leakType = 0;
    if (args.length > 1) {
        leakType = Integer.parseInt(args[1]);
    }//from ww  w .ja  va  2  s.  c  om

    Dictionary newsGroups = new Dictionary();

    encoder.setProbes(2);
    AdaptiveLogisticRegression learningAlgorithm = new AdaptiveLogisticRegression(20, FEATURES, new L1());
    learningAlgorithm.setInterval(800);
    learningAlgorithm.setAveragingWindow(500);

    List<File> files = Lists.newArrayList();
    File[] directories = base.listFiles();
    Arrays.sort(directories, Ordering.usingToString());
    for (File newsgroup : directories) {
        if (newsgroup.isDirectory()) {
            newsGroups.intern(newsgroup.getName());
            files.addAll(Arrays.asList(newsgroup.listFiles()));
        }
    }
    Collections.shuffle(files);
    System.out.printf("%d training files\n", files.size());
    System.out.printf("%s\n", Arrays.asList(directories));

    double averageLL = 0;
    double averageCorrect = 0;

    int k = 0;
    double step = 0;
    int[] bumps = { 1, 2, 5 };
    for (File file : files) {
        String ng = file.getParentFile().getName();
        int actual = newsGroups.intern(ng);

        Vector v = encodeFeatureVector(file);
        learningAlgorithm.train(actual, v);

        k++;

        int bump = bumps[(int) Math.floor(step) % bumps.length];
        int scale = (int) Math.pow(10, Math.floor(step / bumps.length));
        State<AdaptiveLogisticRegression.Wrapper, CrossFoldLearner> best = learningAlgorithm.getBest();
        double maxBeta;
        double nonZeros;
        double positive;
        double norm;

        double lambda = 0;
        double mu = 0;

        if (best != null) {
            CrossFoldLearner state = best.getPayload().getLearner();
            averageCorrect = state.percentCorrect();
            averageLL = state.logLikelihood();

            OnlineLogisticRegression model = state.getModels().get(0);
            // finish off pending regularization
            model.close();

            Matrix beta = model.getBeta();
            maxBeta = beta.aggregate(Functions.MAX, Functions.ABS);
            nonZeros = beta.aggregate(Functions.PLUS, new DoubleFunction() {
                @Override
                public double apply(double v) {
                    return Math.abs(v) > 1.0e-6 ? 1 : 0;
                }
            });
            positive = beta.aggregate(Functions.PLUS, new DoubleFunction() {
                @Override
                public double apply(double v) {
                    return v > 0 ? 1 : 0;
                }
            });
            norm = beta.aggregate(Functions.PLUS, Functions.ABS);

            lambda = learningAlgorithm.getBest().getMappedParams()[0];
            mu = learningAlgorithm.getBest().getMappedParams()[1];
        } else {
            maxBeta = 0;
            nonZeros = 0;
            positive = 0;
            norm = 0;
        }
        if (k % (bump * scale) == 0) {
            if (learningAlgorithm.getBest() != null) {
                ModelSerializer.writeBinary("/tmp/news-group-" + k + ".model",
                        learningAlgorithm.getBest().getPayload().getLearner().getModels().get(0));
            }

            step += 0.25;
            System.out.printf("%.2f\t%.2f\t%.2f\t%.2f\t%.8g\t%.8g\t", maxBeta, nonZeros, positive, norm, lambda,
                    mu);
            System.out.printf("%d\t%.3f\t%.2f\t%s\n", k, averageLL, averageCorrect * 100,
                    LEAK_LABELS[leakType % 3]);
        }
    }
    learningAlgorithm.close();
    dissect(newsGroups, learningAlgorithm, files);
    System.out.println("exiting main");

    ModelSerializer.writeBinary("/tmp/news-group.model",
            learningAlgorithm.getBest().getPayload().getLearner().getModels().get(0));
}

From source file:google.registry.model.SchemaVersion.java

/**
 * Returns a set of classes corresponding to all types persisted within the model classes, sorted
 * by the string representation.//from w w  w. j  ava2s.  c  o  m
 */
private static SortedSet<Class<?>> getAllPersistedTypes() {
    SortedSet<Class<?>> persistedTypes = new TreeSet<>(Ordering.usingToString());
    Queue<Class<?>> queue = new ArrayDeque<>();
    // Do a breadth-first search for persisted types, starting with @Entity types and expanding each
    // ImmutableObject by querying it for all its persisted field types.
    persistedTypes.addAll(EntityClasses.ALL_CLASSES);
    queue.addAll(persistedTypes);
    while (!queue.isEmpty()) {
        Class<?> clazz = queue.remove();
        if (ImmutableObject.class.isAssignableFrom(clazz)) {
            for (Class<?> persistedFieldType : ModelUtils.getPersistedFieldTypes(clazz)) {
                if (persistedTypes.add(persistedFieldType)) {
                    // If we haven't seen this type before, add it to the queue to query its field types.
                    queue.add(persistedFieldType);
                }
            }
        }
    }
    return persistedTypes;
}

From source file:io.crate.testing.SQLPrinter.java

public static String print(Object o) {
    if (o instanceof QuerySpec) {
        return print((QuerySpec) o);
    } else if (o instanceof OrderBy) {
        return print((OrderBy) o);
    } else if (o instanceof Symbol) {
        return print((Symbol) o);
    } else if (o instanceof HashSet) {
        return print(Ordering.usingToString().sortedCopy((HashSet) o));
    } else if (o instanceof Collection) {
        return print((Collection<Symbol>) o);
    } else if (o == null) {
        return "null";
    }/*ww w  . j a  v  a2s . co m*/
    return o.toString();
}

From source file:uk.ac.open.kmi.iserve.discovery.api.ranking.impl.ReverseRanker.java

@Override
public SortedMap<URI, Double> rank(Map<URI, Double> map) {

    Ordering<URI> byScoreOrdering = Ordering.natural().onResultOf(Functions.forMap(map))
            .compound(Ordering.usingToString());

    return ImmutableSortedMap.copyOf(map, byScoreOrdering);
}

From source file:uk.ac.open.kmi.iserve.discovery.api.ranking.impl.StandardRanker.java

@Override
public SortedMap<URI, Double> rank(Map<URI, Double> map) {

    Ordering<URI> byScoreOrdering = Ordering.natural().reverse().onResultOf(Functions.forMap(map))
            .compound(Ordering.usingToString());

    return ImmutableSortedMap.copyOf(map, byScoreOrdering);
}

From source file:org.polarsys.reqcycle.traceability.types.impl.TraceTypesManager.java

@Override
public Iterable<TType> getAllTTypes() {
    return Ordering.usingToString().immutableSortedCopy(map.values());
}

From source file:org.gradle.internal.component.AmbiguousVariantSelectionException.java

public static void formatAttributes(TreeFormatter formatter, AttributeContainer attributes) {
    formatter.startChildren();/*ww w . j av a 2 s.  co m*/
    for (Attribute<?> attribute : Ordering.usingToString().sortedCopy(attributes.keySet())) {
        formatter.node(attribute.getName() + " '" + attributes.getAttribute(attribute) + "'");
    }
    formatter.endChildren();
}

From source file:org.sosy_lab.solver.Model.java

public static void appendModel(Appendable output, Map<AssignableTerm, Object> data) throws IOException {
    Map<AssignableTerm, Object> sorted = ImmutableSortedMap.copyOf(data, Ordering.usingToString());
    joiner.appendTo(output, sorted);//from www.  java 2  s .  c  o m
}

From source file:co.cask.common.cli.completers.StringsCompleter.java

@Override
protected Collection<String> getCandidates(String buffer) {
    List<String> mutableCandidates = Lists.newArrayList();
    for (String candidate : getStrings()) {
        if (candidate.startsWith(buffer)) {
            mutableCandidates.add(candidate);
        }// w w w .ja va 2 s  . c o  m
    }
    Collections.sort(mutableCandidates, Ordering.usingToString());
    return Collections.unmodifiableList(mutableCandidates);
}

From source file:org.polarsys.reqcycle.traceability.types.impl.TraceTypesManager.java

@Override
public Iterable<RegisteredAttribute> getAllAttributes() {
    return Ordering.usingToString().immutableSortedCopy(mapAtt.values());
}