org.tensorflow.Graph.<init>()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(186)

本文整理了Java中org.tensorflow.Graph.<init>()方法的一些代码示例,展示了Graph.<init>()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Graph.<init>()方法的具体详情如下:
包路径:org.tensorflow.Graph
类名称:Graph
方法名:<init>

Graph.<init>介绍

[英]Create an empty Graph.
[中]创建一个空图形。

代码示例

代码示例来源:origin: apache/ignite

/** {@inheritDoc} */
  @Override public Session parseModel(byte[] mdl) {
    Graph graph = new Graph();
    graph.importGraphDef(mdl);

    return new Session(graph);
  }
}

代码示例来源:origin: org.springframework.cloud.stream.app/spring-cloud-starter-stream-common-tensorflow

public TensorFlowService(Resource modelLocation) throws IOException {
  try (InputStream is = modelLocation.getInputStream()) {
    if (logger.isInfoEnabled()) {
      logger.info("Loading TensorFlow graph model: " + modelLocation);
    }
    graph = new Graph();
    graph.importGraphDef(StreamUtils.copyToByteArray(is));
  }
}

代码示例来源:origin: org.tensorflow/libtensorflow

/**
 * Create a SavedModelBundle object from a handle to the C TF_Graph object and to the C TF_Session
 * object, plus the serialized MetaGraphDef.
 *
 * <p>Invoked from the native load method. Takes ownership of the handles.
 */
private static SavedModelBundle fromHandle(
  long graphHandle, long sessionHandle, byte[] metaGraphDef) {
 Graph graph = new Graph(graphHandle);
 Session session = new Session(graph, sessionHandle);
 return new SavedModelBundle(graph, session, metaGraphDef);
}

代码示例来源:origin: org.bytedeco.javacpp-presets/tensorflow

/**
 * Create a SavedModelBundle object from a handle to the C TF_Graph object and to the C TF_Session
 * object, plus the serialized MetaGraphDef.
 *
 * <p>Invoked from the native load method. Takes ownership of the handles.
 */
private static SavedModelBundle fromHandle(
  long graphHandle, long sessionHandle, byte[] metaGraphDef) {
 Graph graph = new Graph(graphHandle);
 Session session = new Session(graph, sessionHandle);
 return new SavedModelBundle(graph, session, metaGraphDef);
}

代码示例来源:origin: spring-cloud-stream-app-starters/tensorflow

public TensorFlowService(Resource modelLocation) {
  if (logger.isInfoEnabled()) {
    logger.info("Loading TensorFlow graph model: " + modelLocation);
  }
  graph = new Graph();
  byte[] model = new ModelExtractor().getModel(modelLocation);
  graph.importGraphDef(model);
}

代码示例来源:origin: org.bytedeco.javacpp-presets/tensorflow

public TensorFlowInferenceInterface(InputStream is) {
 prepareNativeRuntime();
 // modelName is redundant for model loading from input stream, here is for
 // avoiding error in initialization as modelName is marked final.
 this.modelName = "";
 this.g = new Graph();
 this.sess = new Session(g);
 this.runner = sess.runner();
 try {
  if (VERSION.SDK_INT >= 18) {
  }
  int baosInitSize = is.available() > 16384 ? is.available() : 16384;
  ByteArrayOutputStream baos = new ByteArrayOutputStream(baosInitSize);
  int numBytesRead;
  byte[] buf = new byte[16384];
  while ((numBytesRead = is.read(buf, 0, buf.length)) != -1) {
   baos.write(buf, 0, numBytesRead);
  }
  byte[] graphDef = baos.toByteArray();
  if (VERSION.SDK_INT >= 18) {
  }
  loadGraph(graphDef, g);
  Log.i(TAG, "Successfully loaded model from the input stream");
  if (VERSION.SDK_INT >= 18) {
  }
 } catch (IOException e) {
  throw new RuntimeException("Failed to load model from the input stream", e);
 }
}

代码示例来源:origin: spotify/zoltar

/**
 * Note: Please use Models from zoltar-models module.
 *
 * <p>Creates a TensorFlow model based on a frozen, serialized TensorFlow {@link Graph}.
 *
 * @param id model id @{link Model.Id}.
 * @param graphDef byte array representing the TensorFlow {@link Graph} definition.
 * @param config ConfigProto config for TensorFlow {@link Session}.
 * @param prefix a prefix that will be prepended to names in graphDef.
 */
public static TensorFlowGraphModel create(
  final Model.Id id,
  final byte[] graphDef,
  @Nullable final ConfigProto config,
  @Nullable final String prefix)
  throws IOException {
 final Graph graph = new Graph();
 final Session session = new Session(graph, config != null ? config.toByteArray() : null);
 final long loadStart = System.currentTimeMillis();
 if (prefix == null) {
  LOG.debug("Loading graph definition without prefix");
  graph.importGraphDef(graphDef);
 } else {
  LOG.debug("Loading graph definition with prefix: {}", prefix);
  graph.importGraphDef(graphDef, prefix);
 }
 LOG.info("TensorFlow graph loaded in {} ms", System.currentTimeMillis() - loadStart);
 return new AutoValue_TensorFlowGraphModel(id, graph, session);
}

代码示例来源:origin: org.bytedeco.javacpp-presets/tensorflow

this.g = new Graph();
this.sess = new Session(g);
this.runner = sess.runner();

代码示例来源:origin: com.spotify/zoltar-tensorflow

/**
 * Note: Please use Models from zoltar-models module.
 *
 * <p>Creates a TensorFlow model based on a frozen, serialized TensorFlow {@link Graph}.</p>
 *
 * @param id       model id @{link Model.Id}.
 * @param graphDef byte array representing the TensorFlow {@link Graph} definition.
 * @param config   ConfigProto config for TensorFlow {@link Session}.
 * @param prefix   a prefix that will be prepended to names in graphDef.
 */
public static TensorFlowGraphModel create(final Model.Id id,
                     final byte[] graphDef,
                     @Nullable final ConfigProto config,
                     @Nullable final String prefix)
  throws IOException {
 final Graph graph = new Graph();
 final Session session = new Session(graph, config != null ? config.toByteArray() : null);
 final long loadStart = System.currentTimeMillis();
 if (prefix == null) {
  LOG.debug("Loading graph definition without prefix");
  graph.importGraphDef(graphDef);
 } else {
  LOG.debug("Loading graph definition with prefix: {}", prefix);
  graph.importGraphDef(graphDef, prefix);
 }
 LOG.info("TensorFlow graph loaded in {} ms", System.currentTimeMillis() - loadStart);
 return new AutoValue_TensorFlowGraphModel(id, graph, session);
}

代码示例来源:origin: jdye64/nifi-addons

private float[] executeInceptionGraph(byte[] graphDef, Tensor image, String feedNodeName, String outputNodeName) {
  try (Graph g = new Graph()) {
    g.importGraphDef(graphDef);
    try (Session s = new Session(g)) {
      Tensor result = s.runner().feed(feedNodeName, image).fetch(outputNodeName).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];
    }
  }
}

代码示例来源:origin: tahaemara/object-recognition-tensorflow

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

代码示例来源:origin: org.bytedeco.javacpp-presets/tensorflow

private static float[] executeInceptionGraph(byte[] graphDef, Tensor<Float> image) {
 try (Graph g = new Graph()) {
  g.importGraphDef(graphDef);
  try (Session s = new Session(g);
    // Generally, there may be multiple output tensors, all of them must be closed to prevent resource leaks.
    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];
  }
 }
}

代码示例来源:origin: biezhi/java-library-examples

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"));
      }
    }
  }
}

代码示例来源:origin: biezhi/java-library-examples

public static void main(String[] args) {
    /**
     * 定义一个 graph 类,并在这张图上定义了 foo 与 bar 的两个变量
     */
    try (Graph g = new Graph()) {

      try (Tensor<Integer> t = Tensor.create(30, Integer.class)) {
        g.opBuilder("Const", "foo").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      try (Tensor<Integer> t = Tensor.create(20, Integer.class)) {
        g.opBuilder("Const", "bar").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      try (Session s = new Session(g);
         Tensor output1 = s.runner().fetch("foo").run().get(0);
         Tensor output2 = s.runner().fetch("bar").run().get(0)) {

        System.out.println(output1.intValue());
        System.out.println(output2.intValue());
      }
    }
  }
}

代码示例来源:origin: org.springframework.cloud.stream.app/spring-cloud-starter-stream-processor-image-recognition

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));
}

代码示例来源:origin: spring-cloud-stream-app-starters/tensorflow

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));
}

代码示例来源:origin: jdye64/nifi-addons

private Tensor constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
  try (Graph g = new Graph()) {
    GraphBuilder b = new GraphBuilder(g);

代码示例来源:origin: org.bytedeco.javacpp-presets/tensorflow

private static Tensor<Float> constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
 try (Graph g = new Graph()) {
  GraphBuilder b = new GraphBuilder(g);

相关文章