Theano.function equivalent in Tensorflow

孤人 提交于 2019-12-02 06:06:42

The run method on the tf.Session class is quite close to theano.function. Its fetches and feed_dict arguments are moral equivalents of outputs and givens.

Theano's function returns an object that acts like a Python function and executes the computational graph when called. In TensorFlow, you execute computational graph using session's run method. If you want to have a similar Theano-style function object that you can call, you could use TensorFlowTheanoFunction wrapper below as a drop-in replacement for theano's function

class TensorFlowTheanoFunction(object):   
  def __init__(self, inputs, outputs):
    self._inputs = inputs
    self._outputs = outputs

  def __call__(self, *args, **kwargs):
    feeds = {}
    for (argpos, arg) in enumerate(args):
      feeds[self._inputs[argpos]] = arg
    return tf.get_default_session().run(self._outputs, feeds)

a = tf.placeholder(dtype=tf.int32)
b = tf.placeholder(dtype=tf.int32)
c = a+b
d = a-b
sess = tf.InteractiveSession()
f = TensorFlowTheanoFunction([a, b], [c, d])
print f(1, 2)

You will see

[3, -1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!