function — 定义theano.function

指南

此模块提供function(),通常作为theano.function访问,用于将图编译为可调用对象。

你已经看过基本教程中的示例用法... 像下面这样:

>>> import theano
>>> x = theano.tensor.dscalar()
>>> f = theano.function([x], 2*x)
>>> f(4)
array(8.0)

The idea here is that we’ve compiled the symbolic graph (2*x) into a function that can be called on a number and will do some computations.

可以以多种方式控制函数的行为,例如InOutmodeupdatesgivensThese are covered in the tutorial examples and tutorial on modes.

参考

class theano.compile.function.In[source]

A class for attaching information to function inputs.

variable[source]

表达式图中用作编译函数参数的变量

name[source]

A string to identify an argument for this parameter in keyword arguments.

value[source]

The default value to use at call-time (can also be a Container where the function will find a value at call-time.)

update[source]

An expression which indicates updates to the Value after each function call.

mutable[source]

True means the compiled-function is allowed to modify this argument. False means it is not allowed.

borrow[source]

True表示可能会返回对内部存储的引用,并且调用者知道后续函数调用可能会覆盖它的内存。

strict[source]

If False, a function argument may be copied or cast to match the type required by the parameter variable. If True, a function argument must exactly match the type required by variable.

allow_downcast[source]

True indicates that the value you pass for this input can be silently downcasted to fit the right type, which may lose precision. (Only applies when strict is False.)

autoname[source]

True means that the name is set to variable.name.

implicit[source]

True means that the input is implicit in the sense that the user is not allowed to provide a value for it. Requires ‘value’ to be set. False means that the user can provide a value for this input.

__init__(self, variable, name=None, value=None, update=None, mutable=None, strict=False, allow_downcast=None, autoname=True, implicit=None, borrow=None, shared=False)[source]

Initialize attributes from arguments.

class theano.compile.function.Out[source]

A class for attaching information to function outputs

variable[source]

A variable in an expression graph to use as a compiled-function output

borrow[source]

True indicates that a reference to internal storage may be returned, and that the caller is aware that subsequent function evaluations might overwrite this memory.

__init__(variable, borrow=False)[source]

Initialize attributes from arguments.

theano.compile.function.function(inputs, outputs, mode=None, updates=None, givens=None, no_default_updates=False, accept_inplace=False, name=None, rebuild_strict=True, allow_input_downcast=None, profile=None, on_unused_input='raise')[source]

返回一个可调用的对象,它将从inputs计算outputs

Parameters:
  • paramsVariableIn实例的列表, 但不可以是共享变量。) — 返回的Function实例将具有这些变量的参数。
  • outputsVariableOut实例的列表)— 要计算的表达式。
  • mode(None、字符串或Mode实例)。— 编译的模式
  • updates(shared_variable,new_expression)对组成的可迭代对象。列表元组字典。) — 新的SharedVariable值的表达式。
  • givens(Var1,Var2)对组成的可迭代对象。列表元组字典。每个pair中的Var1和Var2必须具有相同的类型。) — 在计算图中要进行的特殊替换(Var2替换Var1)。
  • no_default_updatesboolVariable列表)— 如果为True,不会对变量执行任何自动更新。If False (default), perform them all. Else, perform automatic updates on all Variables that are neither in updates nor in no_default_updates.
  • name —— 此函数的可选名称。profile模式将打印在此函数中花费的时间。
  • rebuild_strict – True (Default) is the safer and better tested setting, in which case givens must substitute new variables with the same Type as the variables they replace. False is a you-better-know-what-you-are-doing setting, that permits givens to replace variables with new variables of any Type. The consequence of changing a Type is that all results depending on that variable may have a different Type too (the graph is rebuilt from inputs to outputs). If one of the new types does not make sense for one of the Ops in the graph, an Exception will be raised.
  • allow_input_downcast (Boolean or None) – True means that the values passed as inputs when calling the function can be silently downcasted to fit the dtype of the corresponding Variable, which may lose precision. False means that it will only be cast to a more general, or precise, type. None (default) is almost like False, but allows downcasting of Python float scalars to floatX.
  • profileNone TrueProfileStats实例) — 将profiling信息累积到给定的ProfileStats实例中。If argument is True then a new ProfileStats instance will be used. 这个profiling对象可通过self.profile访问。
  • on_unused_input — 如果图中没有使用'inputs'列表中的变量,将是什么行为。可能的值为“raise”、“warn”和“ignore”。
Return type:

Function instance

Returns:

一个可计算对象,它将计算输出(给定输入)并根据updates更新隐式函数参数。

inputs可以用变量或In实例给出。In instances also have a variable, but they attach some extra information about how call-time arguments corresponding to that variable should be used. Similarly, Out instances can attach information about how output variables should be returned.

The default is typically ‘FAST_RUN’ but this can be changed in theano.config. mode参数控制将应用于图的优化的种类,以及求值优化图的方式。

在每次函数求值之后,updates机制可以使用从updates列表中的表达式计算的新值替换任何SharedVariable[隐式]输入的值。An exception will be raised if you give two update expressions for the same SharedVariable input (that doesn’t make sense).

If a SharedVariable is not given an update expression, but has a default_update member containing an expression, this expression will be used as the update expression for this variable. Passing no_default_updates=True to function disables this behavior entirely, passing no_default_updates=[sharedvar1, sharedvar2] disables it for the mentioned variables.

关于givens:小心确保这些替换是独立的,因为当一个pair 的Var1出现在导致另一个表达式中的Var2的图中的行为是未定义的(例如,{a: x, b: a + 1})。Replacements specified with givens are different from optimizations in that Var2 is not expected to be equivalent to Var1.

theano.compile.function.function_dump(filename, inputs, outputs=None, mode=None, updates=None, givens=None, no_default_updates=False, accept_inplace=False, name=None, rebuild_strict=True, allow_input_downcast=None, profile=None, on_unused_input=None, extra_tag_to_remove=None)[source]

This is helpful to make a reproducable case for problem during Theano compilation.

Ex:

replace theano.function(...) by theano.function_dump(‘filename.pkl’, ...).

If you see this, you where probably asked to use this function to help debug a particular case during the compilation of a Theano function. function_dump allows to easily reproduce your compilation without asking any code. It pickle all the objects and parameters needed to reproduce a call to theano.function(). This include shared variables and there values. If you do not want that, you can set to replace shared variables values by zeros by calling set_value(...) on them before calling function_dump.

To load such a dump and do the compilation:

>>> from six.moves import cPickle
>>> import theano
>>> d = cPickle.load(open("func_dump.bin", "rb"))  
>>> f = theano.function(**d)  

Note: The parameter extra_tag_to_remove, is passed to the StripPickler used. To pickle graph made by Blocks, it must be: [‘annotations’, ‘replacement_of’, ‘aggregation_scheme’, ‘roles’]

class theano.compile.function_module.Function(fn, input_storage, output_storage, indices, outputs, defaults, unpack_single, return_none, output_keys, maker)[source]

Type of the functions returned by theano.function or theano.FunctionMaker.create.

Function is the callable object that does computation. 它存储输入和输出、进行输入和返回值的打包和解包。It implements the square-bracket indexing so that you can look up the value of a symbolic node.

Functions are copyable via {{{fn.copy()}}} and {{{copy.copy(fn)}}}. 复制函数时,实例将会复制。相反,self.maker(FunctionMaker的实例)在拷贝之间共享。The meaning of copying a function is that the containers and their current values will all be duplicated. This requires that mutable inputs be copied, whereas immutable inputs may be shared between copies.

A Function instance is hashable, on the basis of its memory address (its id).

A Function instance is only equal to itself.

A Function instance may be serialized using the pickle or cPickle modules. This will save all default inputs, the graph, and WRITEME to the pickle file.

A Function instance have a trust_input field that default to False. When True, we don’t do extra check of the input to give better error message. In some case, python code will still return the good results if you pass a python or numpy scalar instead of a numpy tensor. C code should raise an error if you pass an object of the wrong type.

finder[source]
inv_finder[source]
copy(share_memory=False, swap=None, delete_updates=False, name=None, profile=None)[source]

复制此函数。复制的函数和原始的函数将具有独立的make和fgraph。User can choose whether to separate storage by changing the share_memory arguments.

Parameters:
  • share_memoryboolean)— 当为True时,两个函数共享中间存储(除输入和输出存储之外的存储)。否则两个函数将只共享部分存储和相同的maker。If two functions share memory and allow_gc=False, this will increase executing speed and save memory.
  • swapdict)— 将旧的SharedVariables映射到新的SharedVariables的字典。Default is None. NOTE: The shared variable swap in only done in the new returned function, not in the user graph.
  • delete_updatesboolean)— 如果为True,则复制的函数不会带有updates。
  • namestring)— 如果提供,将是新函数的名称。否则,它将旧函数的名字加上“ copy”。
  • profile — 作为theano.function的profile参数
Returns:

Return type:

复制的theano.Function

free()[source]

When allow_gc = False, clear the Variables in storage_map