org.tensorflow.Graph Java Examples
The following examples show how to use
org.tensorflow.Graph.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InstSegMaskRCNN.java From orbit-image-analysis with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) throws IOException { Date startDate = new Date(); InstSegMaskRCNN maskRCNN = new InstSegMaskRCNN(); byte[] graphDef = Files.readAllBytes(Paths.get(MODEL_DIR, MODEL_NAME)); try (Graph g = maskRCNN.loadGraph(graphDef); Session s = maskRCNN.createSession(g)) { BufferedImage originalImage = ImageIO.read(new File(INPUT_IMAGE)); long startt = System.currentTimeMillis(); for (int i=0; i<100; i++) { Tensor<Float> input = maskRCNN.convertBufferedImageToTensor(originalImage); if (input != null) { RawDetections rawDetections = maskRCNN.executeInceptionGraph(s, input); Detections detections = maskRCNN.processDetections(512,512,rawDetections); BufferedImage outputImage = maskRCNN.augmentDetections(originalImage, detections); ImageIO.write(outputImage, "jpg", new File(OUTPUT_IMAGE)); } } long used = System.currentTimeMillis()-startt; System.out.println("time used: "+used/1000d); } long elapsedTimeInSec = (new Date().getTime() - startDate.getTime()) / 1000; System.out.println(String.format("Ended in %ds .", elapsedTimeInSec)); }
Example #2
Source File: RawOpTest.java From java with Apache License 2.0 | 6 votes |
@Test public void equalsHashcode() { try (Graph g = new Graph()) { Ops tf = Ops.create(g); Output<TInt32> array = tf.constant(new int[2]).asOutput(); RawOp test1 = new RawOp(g.opBuilder("Shape", "shape1").addInput(array).build()) {}; RawOp test2 = new RawOp(g.opBuilder("Shape", "shape2").addInput(array).build()) {}; RawOp test3 = new RawOp(test1.operation) {}; // equals() tests assertNotEquals(test1, test2); assertEquals(test1, test3); assertEquals(test3, test1); assertNotEquals(test2, test3); // hashcode() tests Set<RawOp> ops = new HashSet<>(); assertTrue(ops.add(test1)); assertTrue(ops.add(test2)); assertFalse(ops.add(test3)); } }
Example #3
Source File: GradientsTest.java From java with Apache License 2.0 | 6 votes |
@Test public void createGradientsWithInitialValues() { try (Graph g = new Graph(); Session sess = new Session(g)) { Ops tf = Ops.create(g); Output<TFloat32> x = tf.placeholder(TFloat32.DTYPE).output(); Output<TFloat32> y0 = tf.math.square(x).y(); Output<TFloat32> y1 = tf.math.square(y0).y(); Gradients grads0 = Gradients.create(tf.scope(), y1, Arrays.asList(y0)); Gradients grads1 = Gradients.create(tf.scope(), y0, Arrays.asList(x), Gradients.dx(grads0.dy())); assertNotNull(grads1); assertNotNull(grads1.dy()); assertEquals(1, grads1.dy().size()); try (Tensor<TFloat32> c = TFloat32.scalarOf(3.0f); AutoCloseableList<Tensor<?>> outputs = new AutoCloseableList<>( sess.runner().feed(x, c).fetch(grads1.dy(0)).run())) { assertEquals(108.0f, outputs.get(0).expect(TFloat32.DTYPE).data().getFloat(), 0.0f); } } }
Example #4
Source File: ImageRecognitionTensorflowInputConverter.java From tensorflow with Apache License 2.0 | 6 votes |
public ImageRecognitionTensorflowInputConverter() { graph = new Graph(); GraphBuilder b = new GraphBuilder(graph); // Some constants specific to the pre-trained model at: // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip // - The model was trained with images scaled to 224x224 pixels. // - The colors, represented as R, G, B in 1-byte each were converted to // float using (value - Mean)/Scale. final int H = 224; final int W = 224; final float mean = 117f; final float scale = 1f; final Output input = b.placeholder("input", DataType.STRING); graphOutput = b.div( b.sub( b.resizeBilinear( b.expandDims( b.cast(b.decodeJpeg(input, 3), DataType.FLOAT), b.constant("make_batch", 0)), b.constant("size", new int[] { H, W })), b.constant("mean", mean)), b.constant("scale", scale)); }
Example #5
Source File: Gradients.java From java with Apache License 2.0 | 6 votes |
/** * Adds gradients computation ops to the graph according to scope. * * @param scope current graph scope * @param y outputs of the function to derive * @param x inputs of the function for which partial derivatives are computed * @param options carries optional attributes values * @return a new instance of {@code Gradients} * @throws IllegalArgumentException if execution environment is not a graph */ @Endpoint public static Gradients create( Scope scope, Iterable<? extends Operand<?>> y, Iterable<? extends Operand<?>> x, Options... options) { if (!(scope.env() instanceof Graph)) { throw new IllegalArgumentException( "Gradients can be computed only in a graph execution environment"); } Graph graph = (Graph) scope.env(); Output<?>[] dx = null; if (options != null) { for (Options opts : options) { if (opts.dx != null) { dx = Operands.asOutputs(opts.dx); } } } Output<?>[] dy = graph.addGradients( scope.makeOpName("Gradients"), Operands.asOutputs(y), Operands.asOutputs(x), dx); return new Gradients(Arrays.asList(dy)); }
Example #6
Source File: ScopeTest.java From java with Apache License 2.0 | 6 votes |
@Test public void hierarchicalNames() { try (Graph g = new Graph()) { Scope root = new Scope(g); Scope child = root.withSubScope("child"); assertEquals("child/add", child.makeOpName("add")); assertEquals("child/add_1", child.makeOpName("add")); assertEquals("child/mul", child.makeOpName("mul")); Scope child_1 = root.withSubScope("child"); assertEquals("child_1/add", child_1.makeOpName("add")); assertEquals("child_1/add_1", child_1.makeOpName("add")); assertEquals("child_1/mul", child_1.makeOpName("mul")); Scope c_c = root.withSubScope("c").withSubScope("c"); assertEquals("c/c/add", c_c.makeOpName("add")); Scope c_1 = root.withSubScope("c"); Scope c_1_c = c_1.withSubScope("c"); assertEquals("c_1/c/add", c_1_c.makeOpName("add")); Scope c_1_c_1 = c_1.withSubScope("c"); assertEquals("c_1/c_1/add", c_1_c_1.makeOpName("add")); } }
Example #7
Source File: ObjectDetector.java From tensorflow-example-java with Do What The F*ck You Want To Public License | 6 votes |
/** * Pre-process input. It resize the image and normalize its pixels * @param imageBytes Input image * @return Tensor<Float> with shape [1][416][416][3] */ private Tensor<Float> normalizeImage(final byte[] imageBytes) { try (Graph graph = new Graph()) { GraphBuilder graphBuilder = new GraphBuilder(graph); final Output<Float> output = graphBuilder.div( // Divide each pixels with the MEAN graphBuilder.resizeBilinear( // Resize using bilinear interpolation graphBuilder.expandDims( // Increase the output tensors dimension graphBuilder.cast( // Cast the output to Float graphBuilder.decodeJpeg( graphBuilder.constant("input", imageBytes), 3), Float.class), graphBuilder.constant("make_batch", 0)), graphBuilder.constant("size", new int[]{SIZE, SIZE})), graphBuilder.constant("scale", MEAN)); try (Session session = new Session(graph)) { return session.runner().fetch(output.op().name()).run().get(0).expect(Float.class); } } }
Example #8
Source File: ObjectDetector.java From tensorflow-java-examples-spring with Do What The F*ck You Want To Public License | 6 votes |
/** * Pre-process input. It resize the image and normalize its pixels * @param imageBytes Input image * @return Tensor<Float> with shape [1][416][416][3] */ private Tensor<Float> normalizeImage(final byte[] imageBytes) { try (Graph graph = new Graph()) { GraphBuilder graphBuilder = new GraphBuilder(graph); final Output<Float> output = graphBuilder.div( // Divide each pixels with the MEAN graphBuilder.resizeBilinear( // Resize using bilinear interpolation graphBuilder.expandDims( // Increase the output tensors dimension graphBuilder.cast( // Cast the output to Float graphBuilder.decodeJpeg( graphBuilder.constant("input", imageBytes), 3), Float.class), graphBuilder.constant("make_batch", 0)), graphBuilder.constant("size", new int[]{applicationProperties.getImageSize(), applicationProperties.getImageSize()})), graphBuilder.constant("scale", applicationProperties.getImageMean())); try (Session session = new Session(graph)) { return session.runner().fetch(output.op().name()).run().get(0).expect(Float.class); } } }
Example #9
Source File: ConstantTest.java From java with Apache License 2.0 | 6 votes |
@Test public void createFloats() { FloatDataBuffer buffer = DataBuffers.of(1.0f, 2.0f, 3.0f, 4.0f); Shape shape = Shape.of(4); FloatNdArray array = NdArrays.wrap(shape, buffer); try (Graph g = new Graph(); Session sess = new Session(g)) { Scope scope = new Scope(g); Constant<TFloat32> op1 = Constant.tensorOf(scope, shape, buffer); Constant<TFloat32> op2 = Constant.tensorOf(scope, array); try (AutoCloseableList<Tensor<?>> t = new AutoCloseableList<>(sess.runner().fetch(op1).fetch(op2).run())) { assertEquals(array, t.get(0).expect(TFloat32.DTYPE).data()); assertEquals(array, t.get(1).expect(TFloat32.DTYPE).data()); } } }
Example #10
Source File: LabelImage.java From java-ml-projects with Apache License 2.0 | 6 votes |
private float[] executeInceptionGraph(byte[] graphDef, Tensor image) { try (Graph g = new Graph()) { g.importGraphDef(graphDef); try (Session s = new Session(g); Tensor result = s.runner().feed("input", image).fetch("output").run().get(0)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException(String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #11
Source File: ConstantTest.java From java with Apache License 2.0 | 6 votes |
@Test public void createStrings() throws IOException { DataBuffer<String> buffer = DataBuffers.ofObjects("1", "2", "3", "4"); Shape shape = Shape.of(4); NdArray<String> array = NdArrays.wrap(shape, buffer); try (Graph g = new Graph(); Session sess = new Session(g)) { Scope scope = new Scope(g); Constant<TString> op1 = Constant.tensorOf(scope, shape, buffer); Constant<TString> op2 = Constant.tensorOf(scope, array); try (AutoCloseableList<Tensor<?>> t = new AutoCloseableList<>(sess.runner().fetch(op1).fetch(op2).run())) { assertEquals(array, t.get(0).expect(TString.DTYPE).data()); assertEquals(array, t.get(1).expect(TString.DTYPE).data()); } } }
Example #12
Source File: ShapeOpsTest.java From java with Apache License 2.0 | 6 votes |
/** * Test of size method, of class ShapeOps. */ @Test public void testSize_Shape() { try (Graph g = new Graph(); Session session = new Session(g)) { Scope scope = new Scope(g); Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8}); Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1})); Shape<TInt64> tfshape = Shape.create(scope, actual, TInt64.DTYPE); Operand<TInt64> size = ShapeOps.size(scope, tfshape, TInt64.DTYPE); AtomicInteger index = new AtomicInteger(); try (Tensor<TInt64> result1 = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt64.DTYPE)) { result1.data().scalars().forEach(s -> assertEquals(8, s.getLong())); } } }
Example #13
Source File: ShapeOpsTest.java From java with Apache License 2.0 | 6 votes |
/** * Test of size method, of class ShapeOps. */ @Test public void testSize_Operand_Operand() { try (Graph g = new Graph(); Session session = new Session(g)) { Scope scope = new Scope(g); Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8}); Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1})); Operand<TInt32> size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 0)); try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) { result.data().scalars().forEach(s -> assertEquals(4, s.getInt())); } size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 1)); try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) { result.data().scalars().forEach(s -> assertEquals(2, s.getInt())); } size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 2)); try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) { result.data().scalars().forEach(s -> assertEquals(1, s.getInt())); } } }
Example #14
Source File: GeneratedOperationsTest.java From java with Apache License 2.0 | 6 votes |
/** * Test for Ops.withControlDependencies. * * <p>Creates an add node with a control dependency to an assign node. In other words, the assign * node is a control input to the add node. When the add node is run, the assign node is expected * to have run beforehand due to the control dependency. */ @Test public void testControlDependencies() { try (Graph g = new Graph(); Session sess = new Session(g)) { Ops ops = Ops.create(g); Operand<TInt32> variable = ops.variable(Shape.scalar(), TInt32.DTYPE); Operand<?> initVariable = ops.assign(variable, ops.constant(0)); ArrayList<Op> controls = new ArrayList<>(); controls.add(ops.assign(variable, ops.constant(3))); Operand<TInt32> x = ops.withControlDependencies(controls).math.add(variable, ops.constant(0)); sess.runner().addTarget(initVariable).run(); try (Tensor<TInt32> result = sess.runner().fetch(x).run().get(0).expect(TInt32.DTYPE)) { assertEquals(3, result.data().getInt()); } } }
Example #15
Source File: Kafka_Streams_TensorFlow_Image_Recognition_Example.java From kafka-streams-machine-learning-examples with Apache License 2.0 | 6 votes |
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) { try (Graph g = new Graph()) { // Model loading: Using Graph.importGraphDef() to load a pre-trained Inception // model. g.importGraphDef(graphDef); // Graph execution: Using a Session to execute the graphs and find the best // label for an image. try (Session s = new Session(g); Tensor result = s.runner().feed("input", image).fetch("output").run().get(0)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException(String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #16
Source File: Recognizer.java From object-recognition-tensorflow with Apache License 2.0 | 6 votes |
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) { try (Graph g = new Graph()) { g.importGraphDef(graphDef); try (Session s = new Session(g); Tensor result = s.runner().feed("DecodeJpeg/contents", image).fetch("softmax").run().get(0)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException( String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #17
Source File: ShapeOpsTest.java From java with Apache License 2.0 | 6 votes |
/** * Test of flatten method, of class ShapeOps. */ @Test public void testFlatten_Operand() { try (Graph g = new Graph(); Session session = new Session(g)) { Scope scope = new Scope(g); Operand<TFloat32> operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8}); Shape<TInt64> expResult = Shape.create(scope, operand, TInt64.DTYPE); Operand<TFloat32> reshaped = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1})); Operand actual = ShapeOps.flatten(scope, reshaped); Shape<TInt64> tfshape = Shape.create(scope, actual, TInt64.DTYPE); AtomicInteger index = new AtomicInteger(); try (Tensor<TInt64> result1 = session.runner().fetch(tfshape.asOutput()).run().get(0).expect(TInt64.DTYPE); Tensor<TInt64> result2 = session.runner().fetch(expResult.asOutput()).run().get(0).expect(TInt64.DTYPE)) { result1.data().scalars().forEach(s -> assertEquals( result2.data().getLong(index.getAndIncrement()), s.getLong())); } } }
Example #18
Source File: HelloTensorFlow.java From tensorflow-example-java with Do What The F*ck You Want To Public License | 6 votes |
public static void main(String[] args) throws Exception { try (Graph graph = new Graph()) { final String value = "Hello from " + TensorFlow.version(); // Construct the computation graph with a single operation, a constant // named "MyConst" with a value "value". try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) { // The Java API doesn't yet include convenience functions for adding operations. graph.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build(); } // Execute the "MyConst" operation in a Session. try (Session s = new Session(graph); Tensor output = s.runner().fetch("MyConst").run().get(0)) { System.out.println(new String(output.bytesValue(), "UTF-8")); } } }
Example #19
Source File: LabelImage.java From tensorflow-java with MIT License | 6 votes |
private static float[] executeInceptionGraph(byte[] graphDef, Tensor<Float> image) { try (Graph g = new Graph()) { g.importGraphDef(graphDef); try (Session s = new Session(g); Tensor<Float> result = s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException( String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #20
Source File: GraphHelper.java From cineast with MIT License | 6 votes |
/** * filters operations which are not part of a provided graph */ public static List<String> filterOperations(List<String> operations, Graph graph){ if(operations == null || operations.isEmpty() || graph == null){ return Collections.emptyList(); } ArrayList<String> _return = new ArrayList<>(operations.size()); for(String operation : operations){ if(graph.operation(operation) != null){ _return.add(operation); } } return _return; }
Example #21
Source File: Kafka_Streams_TensorFlow_Image_Recognition_Example_IntegrationTest.java From kafka-streams-machine-learning-examples with Apache License 2.0 | 6 votes |
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) { try (Graph g = new Graph()) { g.importGraphDef(graphDef); try (Session s = new Session(g); Tensor result = s.runner().feed("input", image).fetch("output").run().get(0)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException(String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #22
Source File: ImageClassifier.java From video-stream-classification with Apache License 2.0 | 6 votes |
private static float[] executeInceptionGraph(byte[] graphDef, Tensor<Float> image) { try (Graph g = new Graph()) { g.importGraphDef(graphDef); try (Session s = new Session(g); Tensor<Float> result = s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) { final long[] rshape = result.shape(); if (result.numDimensions() != 2 || rshape[0] != 1) { throw new RuntimeException( String.format( "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s", Arrays.toString(rshape))); } int nlabels = (int) rshape[1]; return result.copyTo(new float[1][nlabels])[0]; } } }
Example #23
Source File: AdaGradDA.java From java with Apache License 2.0 | 5 votes |
public AdaGradDA(Graph graph, String name, float learningRate, float initialAccumulatorValue, float l1Strength, float l2Strength) { super(graph, name); this.learningRate = learningRate; this.initialAccumulatorValue = initialAccumulatorValue; this.l1Strength = l1Strength; this.l2Strength = l2Strength; }
Example #24
Source File: Adam.java From java with Apache License 2.0 | 5 votes |
public Adam(Graph graph, String name, float learningRate, float betaOne, float betaTwo, float epsilon) { super(graph, name); this.learningRate = learningRate; this.betaOne = betaOne; this.betaTwo = betaTwo; this.epsilon = epsilon; }
Example #25
Source File: DatasetIteratorTest.java From java with Apache License 2.0 | 5 votes |
@Test public void testGraphIteration() { try (Graph graph = new Graph()) { Ops tf = Ops.create(graph); List<Operand<?>> tensors = Arrays.asList(tf.constant(testMatrix1), tf.constant(testMatrix2)); List<DataType<?>> dataTypes = Arrays.asList(TInt32.DTYPE, TInt32.DTYPE); Dataset dataset = Dataset.fromTensorSlices(tf, tensors, dataTypes); DatasetIterator iterator = dataset.makeOneShotIterator(); List<Operand<?>> components = iterator.getNext(); Operand<?> x = components.get(0); Operand<?> y = components.get(1); try (Session session = new Session(graph)) { session.run(tf.init()); int batches = 0; while (true) { try { List<Tensor<?>> outputs = session.runner().fetch(x).fetch(y).run(); try (Tensor<TInt32> xBatch = outputs.get(0).expect(TInt32.DTYPE); Tensor<TInt32> yBatch = outputs.get(1).expect(TInt32.DTYPE)) { assertEquals(testMatrix1.get(batches), xBatch.data()); assertEquals(testMatrix2.get(batches), yBatch.data()); batches++; } } catch (TFOutOfRangeException e) { break; } } } } }
Example #26
Source File: TensorFlowExtrasTest.java From zoltar with Apache License 2.0 | 5 votes |
private static Graph createDummyGraph() { final Tensor<Double> t2 = Tensors.create(2.0); final Tensor<Double> t3 = Tensors.create(3.0); final Graph graph = new Graph(); final Output<Double> input = graph.opBuilder("Placeholder", "input").setAttr("dtype", DataType.DOUBLE).build().output(0); final Output<Double> two = graph .opBuilder("Const", "two") .setAttr("dtype", t2.dataType()) .setAttr("value", t2) .build() .output(0); final Output<Double> three = graph .opBuilder("Const", "three") .setAttr("dtype", t3.dataType()) .setAttr("value", t3) .build() .output(0); graph.opBuilder("Mul", mul2).addInput(input).addInput(two).build(); graph.opBuilder("Mul", mul3).addInput(input).addInput(three).build(); return graph; }
Example #27
Source File: TensorFlowExtrasTest.java From zoltar with Apache License 2.0 | 5 votes |
@Test public void testExtract1() { final Graph graph = createDummyGraph(); final Session session = new Session(graph); final Session.Runner runner = session.runner(); runner.feed("input", Tensors.create(10.0)); final Map<String, JTensor> result = TensorFlowExtras.runAndExtract(runner, mul2); assertEquals(Sets.newHashSet(mul2), result.keySet()); assertScalar(result.get(mul2), 20.0); session.close(); graph.close(); }
Example #28
Source File: ImageClassifier.java From video-stream-classification with Apache License 2.0 | 5 votes |
private static Tensor<Float> constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) { try (Graph g = new Graph()) { GraphBuilder b = new GraphBuilder(g); // Some constants specific to the pre-trained model at: // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip // // - The model was trained with images scaled to 224x224 pixels. // - The colors, represented as R, G, B in 1-byte each were converted to // float using (value - Mean)/Scale. final int H = 224; final int W = 224; final float mean = 117f; final float scale = 1f; // Since the graph is being constructed once per execution here, we can use a constant for the // input image. If the graph were to be re-used for multiple input images, a placeholder would // have been more appropriate. final Output<String> input = b.constant("input", imageBytes); final Output<Float> output = b.div( b.sub( b.resizeBilinear( b.expandDims( b.cast(b.decodeJpeg(input, 3), Float.class), b.constant("make_batch", 0)), b.constant("size", new int[] {H, W})), b.constant("mean", mean)), b.constant("scale", scale)); try (Session s = new Session(g)) { return s.runner().fetch(output.op().name()).run().get(0).expect(Float.class); } } }
Example #29
Source File: ZerosTest.java From java with Apache License 2.0 | 5 votes |
@Test public void createFloatZeros() { try (Graph g = new Graph(); Session sess = new Session(g)) { Scope scope = new Scope(g); long[] shape = {2, 2}; Zeros<TFloat32> op = Zeros.create(scope, Constant.vectorOf(scope, shape), TFloat32.DTYPE); try (Tensor<TFloat32> result = sess.runner().fetch(op.asOutput()).run().get(0).expect(TFloat32.DTYPE)) { result.data().scalars().forEach(s -> assertEquals(0.0f, s.getFloat(), 0)); } } }
Example #30
Source File: TensorFlowService.java From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
public TensorFlowService(Resource modelLocation) throws IOException { try (InputStream is = modelLocation.getInputStream()) { graph = new Graph(); logger.info("Loading TensorFlow graph model: " + modelLocation); graph.importGraphDef(toByteArray(buffer(is))); logger.info("TensorFlow Graph Model Ready To Serve!"); } }