我正在尝试用Java语言创建一个不使用Python语言的TensorFlow模型。我设法用Java编写了很多Python代码,但是我遗漏了一些要完成的元素。我阻塞了优化器。Python中的原始代码是一个非常简单的模型。
import tensorflow as tf
# Batch of input and target output (1x1 matrices)
x = tf.placeholder(tf.float32, shape=[None, 1, 1], name='input')
y = tf.placeholder(tf.float32, shape=[None, 1, 1], name='target')
# Trivial linear model
y_ = tf.identity(tf.layers.dense(x, 1), name='output')
# Optimize loss
loss = tf.reduce_mean(tf.square(y_ - y), name='loss')
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss, name='train')
init = tf.global_variables_initializer()我开始了向Java的转换,虽然离最后还不远,但我被优化器卡住了。
try (Graph g = new Graph()) {
//# Batch of input and target output (1x1 matrices)
//x = tf.placeholder(tf.float32, shape=[None, 1, 1], name='input')
Output<OperationBuilder> x = g.opBuilder("Placeholder", "input")
.setAttr("dtype", DataType.FLOAT)
.build().output(0);
//y = tf.placeholder(tf.float32, shape=[None, 1, 1], name=target')
Output<OperationBuilder> y = g.opBuilder("Placeholder", "target")
.setAttr("dtype", DataType.FLOAT)
.build().output(0);
//# Trivial linear model
//y_ = tf.identity(tf.layers.dense(x, 1), name='output')
Tensor t = Tensor.create(new int[] {0});
Output reductionIndices = g.opBuilder("Const", "layer")
.setAttr("dtype", t.dataType()).setAttr("value", t)
.build().output(0);
Output dense = g.opBuilder("layersdense", "dense")
.setAttr("T", DataType.FLOAT)
.setAttr("Tidx", DataType.INT32)
.addInput(input).addInput(reductionIndices)
.build().output(0);
Tensor<?> t2 = Tensor.create(dense);
Output<OperationBuilder> y_ = g.opBuilder("Identity", "output")
.setAttr("value", t2)
.build().output(0);
//# Optimize loss
//loss = tf.reduce_mean(tf.square(y_ - y), name='loss')
Output<OperationBuilder> sub=g.opBuilder("Sub","sub")
.addInput(y_).addInput(y)
.build().output(0);
Output<OperationBuilder> sq = g.opBuilder("Square", "Square")
.addInput(sub)
.build().output(0);
//optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
Code java ???
//train_op = optimizer.minimize(loss, name='train')
Code java ???
}发布于 2018-12-21 18:04:15
在对推断的输出进行一些后处理时,我也遇到了很多麻烦。我可以建议的一个解决方案是导入整个图形.pb文件(包括优化器和损失函数的必要节点),该文件是使用python定义的,并在2“s.runner”循环中运行该循环,该循环提供批处理并执行时期。请注意,我还没有尝试过这种方法,但根据我的经验,避免使用特定于java的图形生成器会对您有很大帮助。祝你好运
https://stackoverflow.com/questions/48372361
复制相似问题