Theano.function equivalent in Tensorflow

两盒软妹~` 提交于 2020-01-11 11:51:48

问题


I am wondering if there is any equivalent to

theano.function(inputs=[x,y], # list of input variables
outputs=..., # what values to be returned
updates=..., # “state” values to be modified
givens=...,  # substitutions to the graph)

in TensorFlow


回答1:


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.




回答2:


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]


来源:https://stackoverflow.com/questions/35366970/theano-function-equivalent-in-tensorflow

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