Search in sources :

Example 1 with DAGNetwork

use of com.simiacryptus.mindseye.network.DAGNetwork in project MindsEye by SimiaCryptus.

the class ClassifyProblem method run.

@Nonnull
@Override
public ClassifyProblem run(@Nonnull final NotebookOutput log) {
    @Nonnull final TrainingMonitor monitor = TestUtil.getMonitor(history);
    final Tensor[][] trainingData = getTrainingData(log);
    @Nonnull final DAGNetwork network = fwdFactory.imageToVector(log, categories);
    log.h3("Network Diagram");
    log.code(() -> {
        return Graphviz.fromGraph(TestUtil.toGraph(network)).height(400).width(600).render(Format.PNG).toImage();
    });
    log.h3("Training");
    @Nonnull final SimpleLossNetwork supervisedNetwork = new SimpleLossNetwork(network, new EntropyLossLayer());
    TestUtil.instrumentPerformance(supervisedNetwork);
    int initialSampleSize = Math.max(trainingData.length / 5, Math.min(10, trainingData.length / 2));
    @Nonnull final ValidatingTrainer trainer = optimizer.train(log, new SampledArrayTrainable(trainingData, supervisedNetwork, initialSampleSize, getBatchSize()), new ArrayTrainable(trainingData, supervisedNetwork, getBatchSize()), monitor);
    log.code(() -> {
        trainer.setTimeout(timeoutMinutes, TimeUnit.MINUTES).setMaxIterations(10000).run();
    });
    if (!history.isEmpty()) {
        log.code(() -> {
            return TestUtil.plot(history);
        });
        log.code(() -> {
            return TestUtil.plotTime(history);
        });
    }
    try {
        @Nonnull String filename = log.getName() + "_" + ClassifyProblem.modelNo++ + "_plot.png";
        ImageIO.write(Util.toImage(TestUtil.plot(history)), "png", log.file(filename));
        @Nonnull File file = new File(log.getResourceDir(), filename);
        log.appendFrontMatterProperty("result_plot", file.toString(), ";");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    TestUtil.extractPerformance(log, supervisedNetwork);
    @Nonnull final String modelName = "classification_model_" + ClassifyProblem.modelNo++ + ".json";
    log.appendFrontMatterProperty("result_model", modelName, ";");
    log.p("Saved model as " + log.file(network.getJson().toString(), modelName, modelName));
    log.h3("Validation");
    log.p("If we apply our model against the entire validation dataset, we get this accuracy:");
    log.code(() -> {
        return data.validationData().mapToDouble(labeledObject -> predict(network, labeledObject)[0] == parse(labeledObject.label) ? 1 : 0).average().getAsDouble() * 100;
    });
    log.p("Let's examine some incorrectly predicted results in more detail:");
    log.code(() -> {
        try {
            @Nonnull final TableOutput table = new TableOutput();
            Lists.partition(data.validationData().collect(Collectors.toList()), 100).stream().flatMap(batch -> {
                @Nonnull TensorList batchIn = TensorArray.create(batch.stream().map(x -> x.data).toArray(i -> new Tensor[i]));
                TensorList batchOut = network.eval(new ConstantResult(batchIn)).getData();
                return IntStream.range(0, batchOut.length()).mapToObj(i -> toRow(log, batch.get(i), batchOut.get(i).getData()));
            }).filter(x -> null != x).limit(10).forEach(table::putRow);
            return table;
        } catch (@Nonnull final IOException e) {
            throw new RuntimeException(e);
        }
    });
    return this;
}
Also used : IntStream(java.util.stream.IntStream) Graphviz(guru.nidi.graphviz.engine.Graphviz) EntropyLossLayer(com.simiacryptus.mindseye.layers.java.EntropyLossLayer) Arrays(java.util.Arrays) TableOutput(com.simiacryptus.util.TableOutput) Tensor(com.simiacryptus.mindseye.lang.Tensor) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Lists(com.google.common.collect.Lists) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) Format(guru.nidi.graphviz.engine.Format) LabeledObject(com.simiacryptus.util.test.LabeledObject) TrainingMonitor(com.simiacryptus.mindseye.opt.TrainingMonitor) ImageIO(javax.imageio.ImageIO) SampledArrayTrainable(com.simiacryptus.mindseye.eval.SampledArrayTrainable) Layer(com.simiacryptus.mindseye.lang.Layer) ValidatingTrainer(com.simiacryptus.mindseye.opt.ValidatingTrainer) StepRecord(com.simiacryptus.mindseye.test.StepRecord) NotebookOutput(com.simiacryptus.util.io.NotebookOutput) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Util(com.simiacryptus.util.Util) SimpleLossNetwork(com.simiacryptus.mindseye.network.SimpleLossNetwork) IOException(java.io.IOException) TestUtil(com.simiacryptus.mindseye.test.TestUtil) Collectors(java.util.stream.Collectors) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Stream(java.util.stream.Stream) ArrayTrainable(com.simiacryptus.mindseye.eval.ArrayTrainable) TensorList(com.simiacryptus.mindseye.lang.TensorList) TensorArray(com.simiacryptus.mindseye.lang.TensorArray) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) Comparator(java.util.Comparator) Nonnull(javax.annotation.Nonnull) ConstantResult(com.simiacryptus.mindseye.lang.ConstantResult) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) EntropyLossLayer(com.simiacryptus.mindseye.layers.java.EntropyLossLayer) SampledArrayTrainable(com.simiacryptus.mindseye.eval.SampledArrayTrainable) ArrayTrainable(com.simiacryptus.mindseye.eval.ArrayTrainable) IOException(java.io.IOException) TensorList(com.simiacryptus.mindseye.lang.TensorList) SimpleLossNetwork(com.simiacryptus.mindseye.network.SimpleLossNetwork) TrainingMonitor(com.simiacryptus.mindseye.opt.TrainingMonitor) TableOutput(com.simiacryptus.util.TableOutput) SampledArrayTrainable(com.simiacryptus.mindseye.eval.SampledArrayTrainable) ValidatingTrainer(com.simiacryptus.mindseye.opt.ValidatingTrainer) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 2 with DAGNetwork

use of com.simiacryptus.mindseye.network.DAGNetwork in project MindsEye by SimiaCryptus.

the class DeepDream method getContentComponents.

/**
 * Gets content components.
 *
 * @param setup   the setup
 * @param nodeMap the node map
 * @return the content components
 */
@Nonnull
public ArrayList<Tuple2<Double, DAGNode>> getContentComponents(NeuralSetup<T> setup, final Map<T, DAGNode> nodeMap) {
    ArrayList<Tuple2<Double, DAGNode>> contentComponents = new ArrayList<>();
    for (final T layerType : getLayerTypes()) {
        final DAGNode node = nodeMap.get(layerType);
        if (setup.style.coefficients.containsKey(layerType)) {
            final double coeff_content = setup.style.coefficients.get(layerType).rms;
            DAGNetwork network = node.getNetwork();
            contentComponents.add(new Tuple2<>(coeff_content, network.wrap(new MeanSqLossLayer(), node, network.wrap(new ValueLayer(setup.contentTarget.content.get(layerType))))));
            final double coeff_gain = setup.style.coefficients.get(layerType).gain;
            contentComponents.add(new Tuple2<>(-coeff_gain, network.wrap(new AvgReducerLayer(), network.wrap(new SquareActivationLayer(), node))));
        }
    }
    return contentComponents;
}
Also used : Tuple2(com.simiacryptus.util.lang.Tuple2) AvgReducerLayer(com.simiacryptus.mindseye.layers.cudnn.AvgReducerLayer) ArrayList(java.util.ArrayList) ValueLayer(com.simiacryptus.mindseye.layers.cudnn.ValueLayer) SquareActivationLayer(com.simiacryptus.mindseye.layers.cudnn.SquareActivationLayer) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) DAGNode(com.simiacryptus.mindseye.network.DAGNode) MeanSqLossLayer(com.simiacryptus.mindseye.layers.cudnn.MeanSqLossLayer) Nonnull(javax.annotation.Nonnull)

Example 3 with DAGNetwork

use of com.simiacryptus.mindseye.network.DAGNetwork in project MindsEye by SimiaCryptus.

the class ObjectLocation method run.

/**
 * Run.
 *
 * @param log the log
 */
public void run(@Nonnull final NotebookOutput log) {
    @Nonnull String logName = "cuda_" + log.getName() + ".log";
    log.p(log.file((String) null, logName, "GPU Log"));
    CudaSystem.addLog(new PrintStream(log.file(logName)));
    ImageClassifier classifier = getClassifierNetwork();
    Layer classifyNetwork = classifier.getNetwork();
    ImageClassifier locator = getLocatorNetwork();
    Layer locatorNetwork = locator.getNetwork();
    ArtistryUtil.setPrecision((DAGNetwork) classifyNetwork, Precision.Float);
    ArtistryUtil.setPrecision((DAGNetwork) locatorNetwork, Precision.Float);
    Tensor[][] inputData = loadImages_library();
    // Tensor[][] inputData = loadImage_Caltech101(log);
    double alphaPower = 0.8;
    final AtomicInteger index = new AtomicInteger(0);
    Arrays.stream(inputData).limit(10).forEach(row -> {
        log.h3("Image " + index.getAndIncrement());
        final Tensor img = row[0];
        log.p(log.image(img.toImage(), ""));
        Result classifyResult = classifyNetwork.eval(new MutableResult(row));
        Result locationResult = locatorNetwork.eval(new MutableResult(row));
        Tensor classification = classifyResult.getData().get(0);
        List<CharSequence> categories = classifier.getCategories();
        int[] sortedIndices = IntStream.range(0, categories.size()).mapToObj(x -> x).sorted(Comparator.comparing(i -> -classification.get(i))).mapToInt(x -> x).limit(10).toArray();
        logger.info(Arrays.stream(sortedIndices).mapToObj(i -> String.format("%s: %s = %s%%", i, categories.get(i), classification.get(i) * 100)).reduce((a, b) -> a + "\n" + b).orElse(""));
        Map<CharSequence, Tensor> vectors = new HashMap<>();
        List<CharSequence> predictionList = Arrays.stream(sortedIndices).mapToObj(categories::get).collect(Collectors.toList());
        Arrays.stream(sortedIndices).limit(10).forEach(category -> {
            CharSequence name = categories.get(category);
            log.h3(name);
            Tensor alphaTensor = renderAlpha(alphaPower, img, locationResult, classification, category);
            log.p(log.image(img.toRgbImageAlphaMask(0, 1, 2, alphaTensor), ""));
            vectors.put(name, alphaTensor.unit());
        });
        Tensor avgDetection = vectors.values().stream().reduce((a, b) -> a.add(b)).get().scale(1.0 / vectors.size());
        Array2DRowRealMatrix covarianceMatrix = new Array2DRowRealMatrix(predictionList.size(), predictionList.size());
        for (int x = 0; x < predictionList.size(); x++) {
            for (int y = 0; y < predictionList.size(); y++) {
                Tensor l = vectors.get(predictionList.get(x)).minus(avgDetection);
                Tensor r = vectors.get(predictionList.get(y)).minus(avgDetection);
                covarianceMatrix.setEntry(x, y, l.dot(r));
            }
        }
        @Nonnull final EigenDecomposition decomposition = new EigenDecomposition(covarianceMatrix);
        for (int objectVector = 0; objectVector < 10; objectVector++) {
            log.h3("Eigenobject " + objectVector);
            double eigenvalue = decomposition.getRealEigenvalue(objectVector);
            RealVector eigenvector = decomposition.getEigenvector(objectVector);
            Tensor detectionRegion = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> vectors.get(predictionList.get(i)).scale(eigenvector.getEntry(i))).reduce((a, b) -> a.add(b)).get();
            detectionRegion = detectionRegion.scale(255.0 / detectionRegion.rms());
            CharSequence categorization = IntStream.range(0, eigenvector.getDimension()).mapToObj(i -> {
                CharSequence category = predictionList.get(i);
                double component = eigenvector.getEntry(i);
                return String.format("<li>%s = %.4f</li>", category, component);
            }).reduce((a, b) -> a + "" + b).get();
            log.p(String.format("Object Detected: <ol>%s</ol>", categorization));
            log.p("Object Eigenvalue: " + eigenvalue);
            log.p("Object Region: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion), ""));
            log.p("Object Region Compliment: " + log.image(img.toRgbImageAlphaMask(0, 1, 2, detectionRegion.scale(-1)), ""));
        }
        // final int[] orderedVectors = IntStream.range(0, 10).mapToObj(x -> x)
        // .sorted(Comparator.comparing(x -> -decomposition.getRealEigenvalue(x))).mapToInt(x -> x).toArray();
        // IntStream.range(0, orderedVectors.length)
        // .mapToObj(i -> {
        // //double realEigenvalue = decomposition.getRealEigenvalue(orderedVectors[i]);
        // return decomposition.getEigenvector(orderedVectors[i]).toArray();
        // }
        // ).toArray(i -> new double[i][]);
        log.p(String.format("<table><tr><th>Cosine Distance</th>%s</tr>%s</table>", Arrays.stream(sortedIndices).limit(10).mapToObj(col -> "<th>" + categories.get(col) + "</th>").reduce((a, b) -> a + b).get(), Arrays.stream(sortedIndices).limit(10).mapToObj(r -> {
            return String.format("<tr><td>%s</td>%s</tr>", categories.get(r), Arrays.stream(sortedIndices).limit(10).mapToObj(col -> {
                return String.format("<td>%.4f</td>", Math.acos(vectors.get(categories.get(r)).dot(vectors.get(categories.get(col)))));
            }).reduce((a, b) -> a + b).get());
        }).reduce((a, b) -> a + b).orElse("")));
    });
    log.setFrontMatterProperty("status", "OK");
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Tensor(com.simiacryptus.mindseye.lang.Tensor) VGG16_HDF5(com.simiacryptus.mindseye.models.VGG16_HDF5) HashMap(java.util.HashMap) RealVector(org.apache.commons.math3.linear.RealVector) Caltech101(com.simiacryptus.mindseye.test.data.Caltech101) Result(com.simiacryptus.mindseye.lang.Result) Precision(com.simiacryptus.mindseye.lang.cudnn.Precision) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) Layer(com.simiacryptus.mindseye.lang.Layer) VGG19_HDF5(com.simiacryptus.mindseye.models.VGG19_HDF5) NotebookOutput(com.simiacryptus.util.io.NotebookOutput) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) PrintStream(java.io.PrintStream) Util(com.simiacryptus.util.Util) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) SoftmaxActivationLayer(com.simiacryptus.mindseye.layers.cudnn.SoftmaxActivationLayer) Logger(org.slf4j.Logger) BufferedImage(java.awt.image.BufferedImage) BandReducerLayer(com.simiacryptus.mindseye.layers.cudnn.BandReducerLayer) IOException(java.io.IOException) TestUtil(com.simiacryptus.mindseye.test.TestUtil) Collectors(java.util.stream.Collectors) File(java.io.File) ConvolutionLayer(com.simiacryptus.mindseye.layers.cudnn.ConvolutionLayer) MutableResult(com.simiacryptus.mindseye.lang.MutableResult) Hdf5Archive(com.simiacryptus.mindseye.models.Hdf5Archive) List(java.util.List) Stream(java.util.stream.Stream) CudaSystem(com.simiacryptus.mindseye.lang.cudnn.CudaSystem) EigenDecomposition(org.apache.commons.math3.linear.EigenDecomposition) PoolingLayer(com.simiacryptus.mindseye.layers.cudnn.PoolingLayer) TensorArray(com.simiacryptus.mindseye.lang.TensorArray) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) DeltaSet(com.simiacryptus.mindseye.lang.DeltaSet) Comparator(java.util.Comparator) PrintStream(java.io.PrintStream) Tensor(com.simiacryptus.mindseye.lang.Tensor) MutableResult(com.simiacryptus.mindseye.lang.MutableResult) Nonnull(javax.annotation.Nonnull) HashMap(java.util.HashMap) Layer(com.simiacryptus.mindseye.lang.Layer) SoftmaxActivationLayer(com.simiacryptus.mindseye.layers.cudnn.SoftmaxActivationLayer) BandReducerLayer(com.simiacryptus.mindseye.layers.cudnn.BandReducerLayer) ConvolutionLayer(com.simiacryptus.mindseye.layers.cudnn.ConvolutionLayer) PoolingLayer(com.simiacryptus.mindseye.layers.cudnn.PoolingLayer) Result(com.simiacryptus.mindseye.lang.Result) MutableResult(com.simiacryptus.mindseye.lang.MutableResult) EigenDecomposition(org.apache.commons.math3.linear.EigenDecomposition) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RealVector(org.apache.commons.math3.linear.RealVector)

Example 4 with DAGNetwork

use of com.simiacryptus.mindseye.network.DAGNetwork in project MindsEye by SimiaCryptus.

the class StandardLayerTests method getInvocations.

/**
 * Gets invocations.
 *
 * @param smallLayer the small layer
 * @param smallDims  the small dims
 * @return the invocations
 */
@Nonnull
public Collection<Invocation> getInvocations(@Nonnull Layer smallLayer, @Nonnull int[][] smallDims) {
    @Nonnull DAGNetwork smallCopy = (DAGNetwork) smallLayer.copy();
    @Nonnull HashSet<Invocation> invocations = new HashSet<>();
    smallCopy.visitNodes(node -> {
        @Nullable Layer inner = node.getLayer();
        inner.addRef();
        @Nullable Layer wrapper = new LayerBase() {

            @Nullable
            @Override
            public Result eval(@Nonnull Result... array) {
                if (null == inner)
                    return null;
                @Nullable Result result = inner.eval(array);
                invocations.add(new Invocation(inner, Arrays.stream(array).map(x -> x.getData().getDimensions()).toArray(i -> new int[i][])));
                return result;
            }

            @Override
            public JsonObject getJson(Map<CharSequence, byte[]> resources, DataSerializer dataSerializer) {
                return inner.getJson(resources, dataSerializer);
            }

            @Nullable
            @Override
            public List<double[]> state() {
                return inner.state();
            }

            @Override
            protected void _free() {
                inner.freeRef();
            }
        };
        node.setLayer(wrapper);
        wrapper.freeRef();
    });
    Tensor[] input = Arrays.stream(smallDims).map(i -> new Tensor(i)).toArray(i -> new Tensor[i]);
    try {
        Result eval = smallCopy.eval(input);
        eval.freeRef();
        eval.getData().freeRef();
        return invocations;
    } finally {
        Arrays.stream(input).forEach(ReferenceCounting::freeRef);
        smallCopy.freeRef();
    }
}
Also used : JsonObject(com.google.gson.JsonObject) Graphviz(guru.nidi.graphviz.engine.Graphviz) Arrays(java.util.Arrays) Tensor(com.simiacryptus.mindseye.lang.Tensor) ReferenceCountingBase(com.simiacryptus.mindseye.lang.ReferenceCountingBase) NotebookReportBase(com.simiacryptus.mindseye.test.NotebookReportBase) HashMap(java.util.HashMap) Random(java.util.Random) Result(com.simiacryptus.mindseye.lang.Result) DataSerializer(com.simiacryptus.mindseye.lang.DataSerializer) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Format(guru.nidi.graphviz.engine.Format) Map(java.util.Map) Layer(com.simiacryptus.mindseye.lang.Layer) CudaError(com.simiacryptus.mindseye.lang.cudnn.CudaError) NotebookOutput(com.simiacryptus.util.io.NotebookOutput) ReferenceCounting(com.simiacryptus.mindseye.lang.ReferenceCounting) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) SysOutInterceptor(com.simiacryptus.util.test.SysOutInterceptor) Collection(java.util.Collection) TestUtil(com.simiacryptus.mindseye.test.TestUtil) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) LayerBase(com.simiacryptus.mindseye.lang.LayerBase) Explodable(com.simiacryptus.mindseye.layers.cudnn.Explodable) ToleranceStatistics(com.simiacryptus.mindseye.test.ToleranceStatistics) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) LifecycleException(com.simiacryptus.mindseye.lang.LifecycleException) Tensor(com.simiacryptus.mindseye.lang.Tensor) Nonnull(javax.annotation.Nonnull) DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) Layer(com.simiacryptus.mindseye.lang.Layer) Result(com.simiacryptus.mindseye.lang.Result) ReferenceCounting(com.simiacryptus.mindseye.lang.ReferenceCounting) LayerBase(com.simiacryptus.mindseye.lang.LayerBase) HashMap(java.util.HashMap) Map(java.util.Map) Nullable(javax.annotation.Nullable) HashSet(java.util.HashSet) DataSerializer(com.simiacryptus.mindseye.lang.DataSerializer) Nonnull(javax.annotation.Nonnull)

Example 5 with DAGNetwork

use of com.simiacryptus.mindseye.network.DAGNetwork in project MindsEye by SimiaCryptus.

the class StandardLayerTests method cvt.

/**
 * Cvt nn layer.
 *
 * @param layer the layer
 * @return the nn layer
 */
protected final Layer cvt(Layer layer) {
    if (layer instanceof DAGNetwork) {
        ((DAGNetwork) layer).visitNodes(node -> {
            @Nullable Layer from = node.getLayer();
            node.setLayer(cvt(from));
        });
        return layer;
    } else if (getTestClass().isAssignableFrom(layer.getClass())) {
        @Nullable Class<? extends Layer> referenceLayerClass = getReferenceLayerClass();
        if (null == referenceLayerClass) {
            layer.freeRef();
            return null;
        } else {
            @Nonnull Layer cast = layer.as(referenceLayerClass);
            layer.freeRef();
            return cast;
        }
    } else {
        return layer;
    }
}
Also used : DAGNetwork(com.simiacryptus.mindseye.network.DAGNetwork) Layer(com.simiacryptus.mindseye.lang.Layer) Nullable(javax.annotation.Nullable)

Aggregations

DAGNetwork (com.simiacryptus.mindseye.network.DAGNetwork)19 Nonnull (javax.annotation.Nonnull)16 Layer (com.simiacryptus.mindseye.lang.Layer)11 Nullable (javax.annotation.Nullable)11 Tensor (com.simiacryptus.mindseye.lang.Tensor)10 Arrays (java.util.Arrays)10 List (java.util.List)10 ArrayList (java.util.ArrayList)9 StochasticComponent (com.simiacryptus.mindseye.layers.java.StochasticComponent)7 NotebookOutput (com.simiacryptus.util.io.NotebookOutput)7 Map (java.util.Map)7 TimeUnit (java.util.concurrent.TimeUnit)7 DAGNode (com.simiacryptus.mindseye.network.DAGNode)6 TestUtil (com.simiacryptus.mindseye.test.TestUtil)6 IntStream (java.util.stream.IntStream)6 Format (guru.nidi.graphviz.engine.Format)5 Graphviz (guru.nidi.graphviz.engine.Graphviz)5 File (java.io.File)5 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5