java - 如何在 TensorFlowInferenceInterface 中使用 feed 和 fetch 函数?

标签 java android tensorflow java-native-interface


虽然我想在 TensorFlowInferenceInterface 中使用 feed 和 fetch 函数,但我无法理解 feed 和 fetch 参数。

public void feed(String inputName, float[] src, long... dims) 
public void fetch(String outputName, float[] dst) 

这是TensorflowInferenceInterface。↓ https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/contrib/android/java/org/tensorflow/contrib/android/TensorFlowInferenceInterface.java

现在,我使用 Android-Studio 并希望使用 MNIST 导入程序。
这是制作 Protocol Buffer 的程序。

import tensorflow as tf
import shutil
import os.path

if os.path.exists("./tmp/beginner-export"):
    shutil.rmtree("./tmp/beginner-export")

# Import data
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("./tmp/data/", one_hot=True)

g = tf.Graph()

with g.as_default():
    # Create the model
    x = tf.placeholder("float", [None, 784])
    W = tf.Variable(tf.zeros([784, 10]), name="vaiable_W")
    b = tf.Variable(tf.zeros([10]), name="variable_b")
    y = tf.nn.softmax(tf.matmul(x, W) + b)

    # Define loss and optimizer
    y_ = tf.placeholder("float", [None, 10])
    cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
    train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

    sess = tf.Session()

    # Train
    init = tf.initialize_all_variables()
    sess.run(init)

    for i in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        train_step.run({x: batch_xs, y_: batch_ys}, sess)

    # Test trained model
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

    print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}, sess))

# Store variable
_W = W.eval(sess)
_b = b.eval(sess)

sess.close()

# Create new graph for exporting
g_2 = tf.Graph()
with g_2.as_default():
    # Reconstruct graph
    x_2 = tf.placeholder("float", [None, 784], name="input")
    W_2 = tf.constant(_W, name="constant_W")
    b_2 = tf.constant(_b, name="constant_b")
    y_2 = tf.nn.softmax(tf.matmul(x_2, W_2) + b_2, name="output")

    sess_2 = tf.Session()

    init_2 = tf.initialize_all_variables();
    sess_2.run(init_2)

    graph_def = g_2.as_graph_def()

    tf.train.write_graph(graph_def, './tmp/beginner-export',
                         'beginner-graph.pb', as_text=False)

    # Test trained model
    y__2 = tf.placeholder("float", [None, 10])
    correct_prediction_2 = tf.equal(tf.argmax(y_2, 1), tf.argmax(y__2, 1))
    accuracy_2 = tf.reduce_mean(tf.cast(correct_prediction_2, "float"))
    print(accuracy_2.eval({x_2: mnist.test.images, y__2: mnist.test.labels}, sess_2))

输入的占位符名称是“input”。
输出的占位符名称为“output”。

请告诉我 feed 和 fetch 的用法。

最佳答案

我已经给出了带有注释的示例代码。希望您能理解。

    private static final String INPUT_NODE = "input:0"; // input tensor name
    private static final String OUTPUT_NODE = "output:0"; // output tensor name
    private static final String[] OUTPUT_NODES = {"output:0"}; 
    private static final int OUTPUT_SIZE = 10; // number of classes
    private static final int INPUT_SIZE = 784; // size of the input
    INPUT_IMAGE //MNIST Image
    float[] result = new float[OUTPUT_SIZE]; // get the output probabilities for each class

    inferenceInterface.feed(INPUT_NODE, INPUT_IMAGE, 1, INPUT_SIZE); //1-D input (1,INPUT_SIZE)
    inferenceInterface.run(OUTPUT_NODES);
    inferenceInterface.fetch(OUTPUT_NODE, result);

对于我正在使用的 Android Tensorflow 库版本,我需要提供一维输入。因此,Tensorflow代码需要据此修改,

x_2 = tf.placeholder("float", [None, 1, 784], name="input") //1-D input
x_2 = tf.reshape(x_2,[-1, 784]) // reshape according to the model requirements

希望这有帮助。

关于java - 如何在 TensorFlowInferenceInterface 中使用 feed 和 fetch 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130592/

相关文章:

java - 从 JApplet 读取文件

android - 用于以编程方式更新 apk 的 Xamarin 应用程序

android - 批量删除 Android 中的默认应用程序(使用终端仿真器)

python - Tensorboard - 向数据点添加多个元数据标签

python - tf.scatter_update 或 tf.scatter_nd_update 可以用于更新张量的列切片吗?

Java:如何合并两个 map 的键?

java - 适合保存毫秒数据的容器或数据结构

java - 无法在未指定 LoadTimeWeaver 的情况下应用类转换器

android - 更新应用程序后如何在后台运行服务

每次迭代中的 Tensorflow 内存泄漏