Search in sources :

Example 11 with DoubleSummaryStatistics

use of java.util.DoubleSummaryStatistics in project MindsEye by SimiaCryptus.

the class BasicTrainable method eval.

/**
 * Eval point sample.
 *
 * @param list    the list
 * @param monitor the monitor
 * @return the point sample
 */
@Nonnull
protected PointSample eval(@Nonnull final List<Tensor[]> list, @Nullable final TrainingMonitor monitor) {
    @Nonnull final TimedResult<PointSample> timedResult = TimedResult.time(() -> {
        final Result[] nnContext = BasicTrainable.getNNContext(list, mask);
        final Result result = network.eval(nnContext);
        for (@Nonnull Result nnResult : nnContext) {
            nnResult.getData().freeRef();
            nnResult.freeRef();
        }
        final TensorList resultData = result.getData();
        @Nonnull final DeltaSet<Layer> deltaSet = new DeltaSet<Layer>();
        @Nonnull StateSet<Layer> stateSet = null;
        try {
            final DoubleSummaryStatistics statistics = resultData.stream().flatMapToDouble(x -> {
                double[] array = Arrays.stream(x.getData()).toArray();
                x.freeRef();
                return Arrays.stream(array);
            }).summaryStatistics();
            final double sum = statistics.getSum();
            result.accumulate(deltaSet, 1.0);
            stateSet = new StateSet<>(deltaSet);
            // log.info(String.format("Evaluated to %s delta buffers, %s mag", DeltaSet<LayerBase>.getMap().size(), DeltaSet<LayerBase>.getMagnitude()));
            return new PointSample(deltaSet, stateSet, sum, 0.0, list.size());
        } finally {
            if (null != stateSet)
                stateSet.freeRef();
            resultData.freeRefAsync();
            result.freeRefAsync();
            deltaSet.freeRefAsync();
        }
    });
    if (null != monitor && verbosity() > 0) {
        monitor.log(String.format("Device completed %s items in %.3f sec", list.size(), timedResult.timeNanos / 1e9));
    }
    @Nonnull PointSample normalize = timedResult.result.normalize();
    timedResult.result.freeRef();
    return normalize;
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) Tensor(com.simiacryptus.mindseye.lang.Tensor) ReferenceCountingBase(com.simiacryptus.mindseye.lang.ReferenceCountingBase) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) Result(com.simiacryptus.mindseye.lang.Result) StateSet(com.simiacryptus.mindseye.lang.StateSet) MutableResult(com.simiacryptus.mindseye.lang.MutableResult) List(java.util.List) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) TrainingMonitor(com.simiacryptus.mindseye.opt.TrainingMonitor) TensorList(com.simiacryptus.mindseye.lang.TensorList) TimedResult(com.simiacryptus.util.lang.TimedResult) Layer(com.simiacryptus.mindseye.lang.Layer) TensorArray(com.simiacryptus.mindseye.lang.TensorArray) DeltaSet(com.simiacryptus.mindseye.lang.DeltaSet) Nonnull(javax.annotation.Nonnull) PointSample(com.simiacryptus.mindseye.lang.PointSample) Nullable(javax.annotation.Nullable) Nonnull(javax.annotation.Nonnull) DeltaSet(com.simiacryptus.mindseye.lang.DeltaSet) TensorList(com.simiacryptus.mindseye.lang.TensorList) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) Layer(com.simiacryptus.mindseye.lang.Layer) Result(com.simiacryptus.mindseye.lang.Result) MutableResult(com.simiacryptus.mindseye.lang.MutableResult) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) TimedResult(com.simiacryptus.util.lang.TimedResult) PointSample(com.simiacryptus.mindseye.lang.PointSample) Nonnull(javax.annotation.Nonnull)

Example 12 with DoubleSummaryStatistics

use of java.util.DoubleSummaryStatistics in project MindsEye by SimiaCryptus.

the class TensorListTrainable method eval.

/**
 * Eval point sample.
 *
 * @param list    the list
 * @param monitor the monitor
 * @return the point sample
 */
@Nonnull
protected PointSample eval(@Nonnull final TensorList[] list, @Nullable final TrainingMonitor monitor) {
    int inputs = data.length;
    assert 0 < inputs;
    int items = data[0].length();
    assert 0 < items;
    @Nonnull final TimedResult<PointSample> timedResult = TimedResult.time(() -> {
        final Result[] nnContext = TensorListTrainable.getNNContext(list, mask);
        final Result result = network.eval(nnContext);
        for (@Nonnull Result nnResult : nnContext) {
            nnResult.getData().freeRef();
            nnResult.freeRef();
        }
        final TensorList resultData = result.getData();
        final DoubleSummaryStatistics statistics = resultData.stream().flatMapToDouble(x -> {
            double[] array = Arrays.stream(x.getData()).toArray();
            x.freeRef();
            return Arrays.stream(array);
        }).summaryStatistics();
        final double sum = statistics.getSum();
        @Nonnull final DeltaSet<Layer> deltaSet = new DeltaSet<Layer>();
        @Nonnull PointSample pointSample;
        try {
            result.accumulate(deltaSet, 1.0);
            // log.info(String.format("Evaluated to %s delta buffers, %s mag", DeltaSet<LayerBase>.getMap().size(), DeltaSet<LayerBase>.getMagnitude()));
            @Nonnull StateSet<Layer> stateSet = new StateSet<>(deltaSet);
            pointSample = new PointSample(deltaSet, stateSet, sum, 0.0, items);
            stateSet.freeRef();
        } finally {
            resultData.freeRef();
            result.freeRef();
            deltaSet.freeRef();
        }
        return pointSample;
    });
    if (null != monitor && verbosity() > 0) {
        monitor.log(String.format("Device completed %s items in %.3f sec", items, timedResult.timeNanos / 1e9));
    }
    @Nonnull PointSample normalize = timedResult.result.normalize();
    timedResult.result.freeRef();
    return normalize;
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) Tensor(com.simiacryptus.mindseye.lang.Tensor) ReferenceCountingBase(com.simiacryptus.mindseye.lang.ReferenceCountingBase) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) Result(com.simiacryptus.mindseye.lang.Result) StateSet(com.simiacryptus.mindseye.lang.StateSet) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) TrainingMonitor(com.simiacryptus.mindseye.opt.TrainingMonitor) TensorList(com.simiacryptus.mindseye.lang.TensorList) PlaceholderLayer(com.simiacryptus.mindseye.layers.java.PlaceholderLayer) TimedResult(com.simiacryptus.util.lang.TimedResult) Layer(com.simiacryptus.mindseye.lang.Layer) TensorArray(com.simiacryptus.mindseye.lang.TensorArray) DeltaSet(com.simiacryptus.mindseye.lang.DeltaSet) Nonnull(javax.annotation.Nonnull) PointSample(com.simiacryptus.mindseye.lang.PointSample) Nullable(javax.annotation.Nullable) Nonnull(javax.annotation.Nonnull) DeltaSet(com.simiacryptus.mindseye.lang.DeltaSet) TensorList(com.simiacryptus.mindseye.lang.TensorList) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) PlaceholderLayer(com.simiacryptus.mindseye.layers.java.PlaceholderLayer) Layer(com.simiacryptus.mindseye.lang.Layer) Result(com.simiacryptus.mindseye.lang.Result) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) TimedResult(com.simiacryptus.util.lang.TimedResult) PointSample(com.simiacryptus.mindseye.lang.PointSample) StateSet(com.simiacryptus.mindseye.lang.StateSet) Nonnull(javax.annotation.Nonnull)

Example 13 with DoubleSummaryStatistics

use of java.util.DoubleSummaryStatistics in project MindsEye by SimiaCryptus.

the class DoubleArrayStatsFacade method sumSq.

/**
 * Sum sq double.
 *
 * @return the double
 */
public double sumSq() {
    final DoubleStream doubleStream = Arrays.stream(data).map((final double x) -> x * x);
    final DoubleSummaryStatistics statistics = doubleStream.summaryStatistics();
    return statistics.getSum();
}
Also used : DoubleStream(java.util.stream.DoubleStream) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics)

Example 14 with DoubleSummaryStatistics

use of java.util.DoubleSummaryStatistics in project MindsEye by SimiaCryptus.

the class TestUtil method compareTime.

/**
 * Compare plot canvas.
 *
 * @param title  the title
 * @param trials the trials
 * @return the plot canvas
 */
public static PlotCanvas compareTime(final String title, @Nonnull final ProblemRun... trials) {
    try {
        final DoubleSummaryStatistics[] xStatistics = Arrays.stream(trials).map(x -> x.history.stream().mapToDouble(step -> step.epochTime).filter(Double::isFinite).summaryStatistics()).toArray(i -> new DoubleSummaryStatistics[i]);
        final double totalTime = Arrays.stream(xStatistics).mapToDouble(x -> x.getMax() - x.getMin()).max().getAsDouble();
        final DoubleSummaryStatistics yStatistics = Arrays.stream(trials).flatMapToDouble(x -> x.history.stream().filter(y -> y.fitness > 0).mapToDouble(step -> Math.log10(step.fitness))).filter(Double::isFinite).summaryStatistics();
        if (yStatistics.getCount() == 0) {
            log.info("No Data");
            return null;
        }
        @Nonnull final double[] lowerBound = { 0, yStatistics.getCount() == 0 ? 0 : yStatistics.getMin() };
        @Nonnull final double[] upperBound = { totalTime / 1000.0, yStatistics.getCount() == 1 ? 0 : yStatistics.getMax() };
        @Nonnull final PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound);
        canvas.setTitle(title);
        canvas.setAxisLabels("Time", "log10(Fitness)");
        canvas.setSize(600, 400);
        final List<ProblemRun> filtered = Arrays.stream(trials).filter(x -> !x.history.isEmpty()).collect(Collectors.toList());
        if (filtered.isEmpty()) {
            log.info("No Data");
            return null;
        }
        DoubleSummaryStatistics valueStatistics = filtered.stream().flatMap(x -> x.history.stream()).mapToDouble(x -> x.fitness).filter(x -> x > 0).summaryStatistics();
        log.info(String.format("Plotting range=%s, %s; valueStats=%s", Arrays.toString(lowerBound), Arrays.toString(upperBound), valueStatistics));
        for (int t = 0; t < filtered.size(); t++) {
            final ProblemRun trial = filtered.get(t);
            final DoubleSummaryStatistics trialStats = xStatistics[t];
            final double[][] pts = trial.history.stream().map(step -> {
                return new double[] { (step.epochTime - trialStats.getMin()) / 1000.0, Math.log10(Math.max(step.fitness, valueStatistics.getMin())) };
            }).filter(x -> Arrays.stream(x).allMatch(Double::isFinite)).toArray(i -> new double[i][]);
            if (pts.length > 1) {
                log.info(String.format("Plotting %s points for %s", pts.length, trial.name));
                canvas.add(trial.plot(pts));
            } else {
                log.info(String.format("Only %s points for %s", pts.length, trial.name));
            }
        }
        return canvas;
    } catch (@Nonnull final Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
}
Also used : Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) DoubleStatistics(com.simiacryptus.util.data.DoubleStatistics) IntUnaryOperator(java.util.function.IntUnaryOperator) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) TrainingMonitor(com.simiacryptus.mindseye.opt.TrainingMonitor) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) Layer(com.simiacryptus.mindseye.lang.Layer) URI(java.net.URI) Graph(guru.nidi.graphviz.model.Graph) LongToIntFunction(java.util.function.LongToIntFunction) StochasticComponent(com.simiacryptus.mindseye.layers.java.StochasticComponent) BufferedImage(java.awt.image.BufferedImage) UUID(java.util.UUID) ComponentEvent(java.awt.event.ComponentEvent) WindowAdapter(java.awt.event.WindowAdapter) DAGNode(com.simiacryptus.mindseye.network.DAGNode) Collectors(java.util.stream.Collectors) WindowEvent(java.awt.event.WindowEvent) Executors(java.util.concurrent.Executors) List(java.util.List) Stream(java.util.stream.Stream) ScalarStatistics(com.simiacryptus.util.data.ScalarStatistics) LoggingWrapperLayer(com.simiacryptus.mindseye.layers.java.LoggingWrapperLayer) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) IntStream(java.util.stream.IntStream) MonitoringWrapperLayer(com.simiacryptus.mindseye.layers.java.MonitoringWrapperLayer) ActionListener(java.awt.event.ActionListener) ScatterPlot(smile.plot.ScatterPlot) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LinkSource(guru.nidi.graphviz.model.LinkSource) Tensor(com.simiacryptus.mindseye.lang.Tensor) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) JsonUtil(com.simiacryptus.util.io.JsonUtil) MutableNode(guru.nidi.graphviz.model.MutableNode) Charset(java.nio.charset.Charset) Factory(guru.nidi.graphviz.model.Factory) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NotebookOutput(com.simiacryptus.util.io.NotebookOutput) WeakReference(java.lang.ref.WeakReference) LinkTarget(guru.nidi.graphviz.model.LinkTarget) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) LongSummaryStatistics(java.util.LongSummaryStatistics) PrintStream(java.io.PrintStream) Logger(org.slf4j.Logger) PlotCanvas(smile.plot.PlotCanvas) RankDir(guru.nidi.graphviz.attribute.RankDir) IOException(java.io.IOException) FileFilter(javax.swing.filechooser.FileFilter) ActionEvent(java.awt.event.ActionEvent) PercentileStatistics(com.simiacryptus.util.data.PercentileStatistics) File(java.io.File) java.awt(java.awt) ComponentAdapter(java.awt.event.ComponentAdapter) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MonitoredObject(com.simiacryptus.util.MonitoredObject) IntToLongFunction(java.util.function.IntToLongFunction) Link(guru.nidi.graphviz.model.Link) Step(com.simiacryptus.mindseye.opt.Step) Comparator(java.util.Comparator) javax.swing(javax.swing) Nonnull(javax.annotation.Nonnull) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics) IOException(java.io.IOException) PlotCanvas(smile.plot.PlotCanvas)

Example 15 with DoubleSummaryStatistics

use of java.util.DoubleSummaryStatistics in project guava by google.

the class StatsTest method testEquivalentStreams.

public void testEquivalentStreams() {
    // and non-finite values:
    for (ManyValues values : ALL_MANY_VALUES) {
        double[] array = values.asArray();
        Stats stats = Stats.of(array);
        // instance methods on Stats vs on instance methods on DoubleStream
        assertThat(stats.count()).isEqualTo(stream(array).count());
        assertEquivalent(stats.mean(), stream(array).average().getAsDouble());
        assertEquivalent(stats.sum(), stream(array).sum());
        assertEquivalent(stats.max(), stream(array).max().getAsDouble());
        assertEquivalent(stats.min(), stream(array).min().getAsDouble());
        // static method on Stats vs on instance method on DoubleStream
        assertEquivalent(Stats.meanOf(array), stream(array).average().getAsDouble());
        // instance methods on Stats vs instance methods on DoubleSummaryStatistics
        DoubleSummaryStatistics streamStats = stream(array).summaryStatistics();
        assertThat(stats.count()).isEqualTo(streamStats.getCount());
        assertEquivalent(stats.mean(), streamStats.getAverage());
        assertEquivalent(stats.sum(), streamStats.getSum());
        assertEquivalent(stats.max(), streamStats.getMax());
        assertEquivalent(stats.min(), streamStats.getMin());
    }
}
Also used : ManyValues(com.google.common.math.StatsTesting.ManyValues) Stats.toStats(com.google.common.math.Stats.toStats) DoubleSummaryStatistics(java.util.DoubleSummaryStatistics)

Aggregations

DoubleSummaryStatistics (java.util.DoubleSummaryStatistics)39 Arrays (java.util.Arrays)9 List (java.util.List)9 Test (org.junit.Test)9 Layer (com.simiacryptus.mindseye.lang.Layer)8 Tensor (com.simiacryptus.mindseye.lang.Tensor)8 LongSummaryStatistics (java.util.LongSummaryStatistics)8 IntStream (java.util.stream.IntStream)8 Nonnull (javax.annotation.Nonnull)8 Nullable (javax.annotation.Nullable)8 TrainingMonitor (com.simiacryptus.mindseye.opt.TrainingMonitor)7 Map (java.util.Map)6 LoggingWrapperLayer (com.simiacryptus.mindseye.layers.java.LoggingWrapperLayer)5 MonitoringWrapperLayer (com.simiacryptus.mindseye.layers.java.MonitoringWrapperLayer)5 StochasticComponent (com.simiacryptus.mindseye.layers.java.StochasticComponent)5 DAGNetwork (com.simiacryptus.mindseye.network.DAGNetwork)5 DAGNode (com.simiacryptus.mindseye.network.DAGNode)5 Step (com.simiacryptus.mindseye.opt.Step)5 MonitoredObject (com.simiacryptus.util.MonitoredObject)5 DoubleStatistics (com.simiacryptus.util.data.DoubleStatistics)5