当前位置: 首页>>代码示例>>Java>>正文


Java Session类代码示例

本文整理汇总了Java中org.tensorflow.Session的典型用法代码示例。如果您正苦于以下问题:Java Session类的具体用法?Java Session怎么用?Java Session使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Session类属于org.tensorflow包,在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: Inception

import org.tensorflow.Session; //导入依赖的package包/类
public Inception(String graphPath, String labelsPath) throws IOException{
    graphDef = Files.readAllBytes(Paths.get(graphPath));
    labels = Files.readAllLines(Paths.get(labelsPath));

    Graph g = new Graph();
    s = new Session(g);
    GraphBuilder b = new GraphBuilder(g);
    // - 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;
    output = b.div(
                b.sub(
                    b.resizeBilinear(
                            b.expandDims(
                                    b.cast(b.decodeJpeg(b.placeholder("input", DataType.STRING), 3), DataType.FLOAT),
                                    b.constant("make_batch", 0)),
                            b.constant("size", new int[] {H, W})),
                    b.constant("mean", mean)),
                b.constant("scale", scale));
}
 
开发者ID:alseambusher,项目名称:TensorFlow-models4j,代码行数:25,代码来源:Inception.java

示例2: main

import org.tensorflow.Session; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    try (Graph g = 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.
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(g);
             Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            System.out.println(new String(output.bytesValue(), "UTF-8"));
        }
    }
}
 
开发者ID:neo4j-contrib,项目名称:neo4j-ml-procedures,代码行数:19,代码来源:HelloTF.java

示例3: executeInceptionGraph

import org.tensorflow.Session; //导入依赖的package包/类
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];
        }
    }
}
 
开发者ID:emara-geek,项目名称:object-recognition-tensorflow,代码行数:18,代码来源:Recognizer.java

示例4: createContext

import org.tensorflow.Session; //导入依赖的package包/类
private static TfContext createContext(ReactContext reactContext, String model) throws IOException {
    byte[] b = new ResourceManager(reactContext.getAssets()).loadResource(model);

    Graph graph = new Graph();
    graph.importGraphDef(b);
    Session session = new Session(graph);
    Session.Runner runner = session.runner();

    return new TfContext(session, runner, graph);
}
 
开发者ID:reneweb,项目名称:react-native-tensorflow,代码行数:11,代码来源:RNTensorflowInference.java

示例5: constructAndExecuteGraphToNormalizeImage

import org.tensorflow.Session; //导入依赖的package包/类
private Tensor 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 input = b.constant("input", imageBytes);
		final Output output = 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));
		try (Session s = new Session(g)) {
			return s.runner().fetch(output.op().name()).run().get(0);
		}
	}
}
 
开发者ID:jesuino,项目名称:java-ml-projects,代码行数:32,代码来源:LabelImage.java

示例6: executeInceptionGraph

import org.tensorflow.Session; //导入依赖的package包/类
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];
		}
	}
}
 
开发者ID:jesuino,项目名称:java-ml-projects,代码行数:17,代码来源:LabelImage.java

示例7: getInception

import org.tensorflow.Session; //导入依赖的package包/类
public List<Entry<Float, String>> getInception(byte[] imageBytes, String modelDir) {
	logger.info(String.format("getInception: %d bytes %s", new Object[] { imageBytes.length, Paths.get(modelDir, "graph.pb") }));
	Graph g = getOrCreate(Paths.get(modelDir, "graph.pb"));
	try (Session s = new Session(g)) {
		List<String> labels = getOrCreateLabels(Paths.get(modelDir, "label.txt"));
		Tensor image = constructAndExecuteGraphToNormalizeImage(imageBytes);
		Tensor result = s.runner().feed("input", image).fetch("output").run().get(0);
		logger.debug("found results");

		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];

		logger.debug(String.format("number of labels %d, %d", new Object[] { labels.size(), nlabels }));
		int mLabeled = Math.min(labels.size(), nlabels);

		float[] labelProbabilities = result.copyTo(new float[1][nlabels])[0];

		HashMap<Float, String> results = new HashMap<Float, String>();
		for (int i = 0; i < mLabeled; i++) {
			results.put(labelProbabilities[i], labels.get(i));
		}

		return Collections.synchronizedList(
				results.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).limit(10)
						.collect(Collectors.toList()));
	} catch (Exception e) {
		logger.error("Failed in tensorflow", e);
		throw(e);
	}
}
 
开发者ID:tspannhw,项目名称:nifi-tensorflow-processor,代码行数:36,代码来源:TensorFlowService.java

示例8: constructAndExecuteGraphToNormalizeImage

import org.tensorflow.Session; //导入依赖的package包/类
private static Tensor 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 input = b.constant("input", imageBytes);
		final Output output = 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));
		try (Session s = new Session(g)) {
			return s.runner().fetch(output.op().name()).run().get(0);
		}
	}
}
 
开发者ID:tspannhw,项目名称:nifi-tensorflow-processor,代码行数:31,代码来源:TensorFlowService.java

示例9: testTf

import org.tensorflow.Session; //导入依赖的package包/类
@Test
public void testTf() throws UnsupportedEncodingException {
    try (Graph g = 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.
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(g); Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            logger.info(new String(output.bytesValue(), "UTF-8"));
            logger.info(output.toString());
        }
    }
}
 
开发者ID:softelnet,项目名称:sponge,代码行数:20,代码来源:TensorflowTest.java

示例10: executeInceptionGraph

import org.tensorflow.Session; //导入依赖的package包/类
private static float[] executeInceptionGraph(final Graph g,
	final Tensor image)
{
	try (
		final Session s = new Session(g);
		final 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)));
		}
		final int nlabels = (int) rshape[1];
		return result.copyTo(new float[1][nlabels])[0];
	}
}
 
开发者ID:imagej,项目名称:imagej-tensorflow,代码行数:21,代码来源:LabelImage.java

示例11: constructAndExecuteGraphToNormalizeRGBImage

import org.tensorflow.Session; //导入依赖的package包/类
public static Tensor<Float> constructAndExecuteGraphToNormalizeRGBImage(byte[] imageBytes, int W, int H, float mean, float scale) {
        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);
            }
        }
    }
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:34,代码来源:TensorFlow.java

示例12: executeGraph

import org.tensorflow.Session; //导入依赖的package包/类
public static float[] executeGraph(Graph graph, Tensor<Float> image, String inputLayerName, String outputLayerName) {
//        try (Graph g=graph) {
            try (Session s = new Session(graph);
                    Tensor<Float> result = s.runner().feed(inputLayerName, image).fetch(outputLayerName).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];
            }
//        }
    }
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:18,代码来源:TensorFlow.java

示例13: constructAndExecuteGraphToNormalizeImage

import org.tensorflow.Session; //导入依赖的package包/类
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);
        }
    }
}
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:34,代码来源:LabelImage.java

示例14: executeInceptionGraph

import org.tensorflow.Session; //导入依赖的package包/类
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];
        }
    }
}
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:19,代码来源:LabelImage.java

示例15: main

import org.tensorflow.Session; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    try (Graph g = 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.
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(g);
                Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            System.out.println(new String(output.bytesValue(), "UTF-8"));
        }
    }
}
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:19,代码来源:HelloTF.java


注:本文中的org.tensorflow.Session类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。