type
– Interface for types of variables¶
Reference¶
The Type classes.
-
class
theano.graph.type.
CDataType
(ctype, freefunc=None, headers=(), header_dirs=(), libraries=(), lib_dirs=(), compile_args=(), extra_support_code='', version=None)[source]¶ Represents opaque C data to be passed around. The intent is to ease passing arbitrary data between ops C code.
The constructor builds a type made to represent a C pointer in theano.
Parameters: - ctype – The type of the pointer (complete with the *).
- freefunc – A function to call to free the pointer. This function must have a void return and take a single pointer argument.
- version – The version to use in Theano cache system.
-
Constant
[source]¶ alias of
theano.graph.type.CDataTypeConstant
-
c_cleanup
(name, sub)[source]¶ Return C code to clean up after CLinkerType.c_extract.
This returns C code that should deallocate whatever CLinkerType.c_extract allocated or decrease the reference counts. Do not decrease
py_%(name)s
’s reference count.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
c_code_cache_version
()[source]¶ Return a tuple of integers indicating the version of this type.
An empty tuple indicates an ‘unversioned’ type that will not be cached between processes.
The cache mechanism may erase cached modules that have been superceded by newer versions. See ModuleCache for details.
-
c_compile_args
(**kwargs)[source]¶ Return a list of recommended compile arguments for code returned by other methods in this class.
Compiler arguments related to headers, libraries and search paths should be provided via the functions c_headers, c_libraries, c_header_dirs, and c_lib_dirs.
Examples
- def c_compile_args(self, **kwargs):
- return [‘-ffast-math’]
-
c_declare
(name, sub, check_input=True)[source]¶ Return C code to declare variables that will be instantiated by CLinkerType.c_extract.
Parameters: - name (str) – The name of the
PyObject *
pointer that will the value for this Type - sub (dict string -> string) – a dictionary of special codes. Most importantly
sub[‘fail’]. See CLinker for more info on sub and
fail
.
Notes
It is important to include the name inside of variables which are declared here, so that name collisions do not occur in the source file that is generated.
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted to create class variables for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable declaration fail? Is it even allowed to?
Examples
- name (str) – The name of the
-
c_extract
(name, sub, check_input=True, **kwargs)[source]¶ Return C code to extract a
PyObject *
instance.The code returned from this function must be templated using
%(name)s
, representing the name that the caller wants to call this Variable. The Python objectself.data
is in a variable called"py_%(name)s"
and this code must set the variables declared by c_declare to something representative ofpy_%(name)``s. If the data is improper, set an appropriate exception and insert ``"%(fail)s"
.TODO: Point out that template filling (via sub) is now performed by this function. –jpt
Parameters: - name (str) – The name of the
PyObject *
pointer that will store the value for this type. - sub (dict string -> string) – A dictionary of special codes. Most importantly
sub['fail']
. See CLinker for more info onsub
andfail
.
Examples
- name (str) – The name of the
-
c_header_dirs
(**kwargs)[source]¶ Return a list of header search paths required by code returned by this class.
Provides search paths for headers, in addition to those in any relevant environment variables.
Note: for Unix compilers, these are the things that get -I prefixed in the compiler command line arguments.
Examples
- def c_header_dirs(self, **kwargs):
- return [‘/usr/local/include’, ‘/opt/weirdpath/src/include’]
-
c_headers
(**kwargs)[source]¶ Return a list of header files required by code returned by this class.
These strings will be prefixed with
#include
and inserted at the beginning of the C source code.Strings in this list that start neither with
<
nor"
will be enclosed in double-quotes.Examples
- def c_headers(self, **kwargs):
- return [‘<iostream>’, ‘<math.h>’, ‘/full/path/to/header.h’]
-
c_init
(name, sub)[source]¶ Return C code to initialize the variables that were declared by CLinkerType.c_declare.
Notes
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted in a class constructor for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable initialization fail? Is it even allowed to?
Examples
-
c_lib_dirs
(**kwargs)[source]¶ Return a list of library search paths required by code returned by this class.
Provides search paths for libraries, in addition to those in any relevant environment variables (e.g.
LD_LIBRARY_PATH
).Note: for Unix compilers, these are the things that get
-L
prefixed in the compiler command line arguments.Examples
- def c_lib_dirs(self, **kwargs):
- return [‘/usr/local/lib’, ‘/opt/weirdpath/build/libs’].
-
c_libraries
(**kwargs)[source]¶ Return a list of libraries required by code returned by this class.
The compiler will search the directories specified by the environment variable LD_LIBRARY_PATH in addition to any returned by c_lib_dirs.
Note: for Unix compilers, these are the things that get
-l
prefixed in the compiler command line arguments.Examples
- def c_libraries(self, **kwargs):
- return [‘gsl’, ‘gslcblas’, ‘m’, ‘fftw3’, ‘g2c’].
-
c_support_code
(**kwargs)[source]¶ Return utility code for use by a Variable or Op.
This is included at global scope prior to the rest of the code for this class.
Question: How many times will this support code be emitted for a graph with many instances of the same type?
Return type: str
-
c_sync
(name, sub)[source]¶ Return C code to pack C types back into a
PyObject
.The code returned from this function must be templated using
"%(name)s"
, representing the name that the caller wants to call this Variable. The returned code may set"py_%(name)s"
to aPyObject*
and thatPyObject*
will be accessible from Python viavariable.data
. Do not forget to adjust reference counts if"py_%(name)s"
is changed from its original value.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
filter
(data, strict=False, allow_downcast=None)[source]¶ Return data or an appropriately wrapped/converted data.
Subclass implementations should raise a TypeError exception if the data is not of an acceptable type.
Parameters: - data (array-like) – The data to be filtered/converted.
- strict (bool (optional)) – If
True
, the data returned must be the same as the data passed as an argument. - allow_downcast (bool (optional)) – If strict is
False
, and allow_downcast isTrue
, the data may be cast to an appropriate type. If allow_downcast isFalse
, it may only be up-cast and not lose precision. If allow_downcast isNone
(default), the behaviour can be type-dependent, but for now it means only Python floats can be down-casted, and only to floatX scalars.
-
class
theano.graph.type.
CEnumType
(*args, **kwargs)[source]¶ - Inherit from:
Op parameter class that allows to create enumeration of constant values that represent C-defined constants.
- Constant should have same names as in C.
- In Python, constants will have arbitrary-defined values. They should be used only for choices, not for its values.
- In C code, the real values defined in C will be used. They could be used either for choices or for its real values.
Like
EnumList
, you can also define the C type and a C name for the op param. Default C type isint
.enum = CEnumType('CONSTANT_CNAME_1', 'CONSTANT_CNAME_2', 'CONSTANT_CNAME_3', ctype='long')
Like
EnumList
, you can also add an alias to a constant, with same syntax as inEnumList
.See test
tests.graph.test_types.TestEnumTypes.test_op_with_cenumtype()
for a working example.Note
Be sure C constants are available in your C code. If they come from a C header, consider implementing
c_headers()
andc_header_dirs()
in the Op class where you use CEnumType as op parameter type.-
c_code_cache_version
()[source]¶ Return a tuple of integers indicating the version of this type.
An empty tuple indicates an ‘unversioned’ type that will not be cached between processes.
The cache mechanism may erase cached modules that have been superceded by newer versions. See ModuleCache for details.
-
c_extract
(name, sub, check_input=True, **kwargs)[source]¶ Return C code to extract a
PyObject *
instance.The code returned from this function must be templated using
%(name)s
, representing the name that the caller wants to call this Variable. The Python objectself.data
is in a variable called"py_%(name)s"
and this code must set the variables declared by c_declare to something representative ofpy_%(name)``s. If the data is improper, set an appropriate exception and insert ``"%(fail)s"
.TODO: Point out that template filling (via sub) is now performed by this function. –jpt
Parameters: - name (str) – The name of the
PyObject *
pointer that will store the value for this type. - sub (dict string -> string) – A dictionary of special codes. Most importantly
sub['fail']
. See CLinker for more info onsub
andfail
.
Examples
- name (str) – The name of the
-
class
theano.graph.type.
CType
[source]¶ Convenience wrapper combining Type and CLinkerType.
Theano comes with several subclasses of such as:
- Generic: for any python type
- TensorType: for numpy.ndarray
- SparseType: for scipy.sparse
But you are encouraged to write your own, as described in WRITEME.
The following code illustrates the use of a Type instance, here tensor.fvector:
# Declare a symbolic floating-point vector using __call__ b = tensor.fvector() # Create a second Variable with the same Type instance c = tensor.fvector()
Whenever you create a symbolic variable in theano (technically, Variable) it will contain a reference to a Type instance. That reference is typically constant during the lifetime of the Variable. Many variables can refer to a single Type instance, as do b and c above. The Type instance defines the kind of value which might end up in that variable when executing a Function. In this sense, theano is like a strongly-typed language because the types are included in the graph before the values. In our example above, b is a Variable which is guaranteed to correspond to a numpy.ndarray of rank 1 when we try to do some computations with it.
Many Op instances will raise an exception if they are applied to inputs with incorrect types. Type references are also useful to do type-checking in pattern-based optimizations.
-
class
theano.graph.type.
EnumList
(*args, **kwargs)[source]¶ - Inherit from:
Op parameter class that allows to create enumeration of constant values. Same as
EnumType
, but automatically gives an unique integer value for each constant in a list of constants names (constant at indexi
in the list will receive valuei
, withi
from0
tolen(constants) - 1
).Example:
enum = EnumList('CONSTANT_1', 'CONSTANT_2', 'CONSTANT_3', 'CONSTANT_4', 'CONSTANT_5') print (enum.CONSTANT_1, enum.CONSTANT_2, enum.CONSTANT_3, enum.CONSTANT_4, enum.CONSTANT_5) # will print: 0 1 2 3 4
Like
EnumType
, you can also define the C type and a C name for the op param. Default C type isint
:enum = EnumList('CONSTANT_1', 'CONSTANT_2', 'CONSTANT_3', 'CONSTANT_4', ctype='unsigned int')
Like
EnumType
, you can also add an alias to a constant, by replacing the only constant name (e.g.'CONSTANT_NAME'
) by a couple with constant name first and constant alias second (e.g.('CONSTANT_NAME', 'constant_alias')
).enum = EnumList(('A', 'alpha'), ('B', 'beta'), 'C', 'D', 'E', 'F', ('G', 'gamma'))
See test class
tests.graph.test_types.TestOpEnumList
for a working example.
-
class
theano.graph.type.
EnumType
(**kwargs)[source]¶ -
Op parameter class that allows to create enumerations of constant values.
- Constants are available as object attributes in Python code and as macro-defined constants in C code.
- Constants can be floating values, integers, or booleans (automatically converted to integers).
- Constants name must start with a capital letter and contain capital letters, underscores or digits.
- A constant can have an alias, and then be available through both constant name and constant alias.
Example
enum = EnumType(CONSTANT_1=1, CONSTANT_2=2.5, CONSTANT_3=False, CONSTANT_4=True) print (enum.CONSTANT_1, enum.CONSTANT_2, enum.CONSTANT_3, enum.CONSTANT_4) # will print 1 2.5 0 1
In C code:
int constant_1 = CONSTANT_1; double constant_2 = CONSTANT_2; int constant_3 = CONSTANT_3; // constant_3 == 0 int constant_4 = CONSTANT_4; // constant_4 == 1
You can also specify a C type for the op param. Default C type is
double
.enum = EnumType(CONSTANT_1=0, CONSTANT_2=1, CONSTANT_3=2, ctype='size_t') # In C code, the Op param will then be a ``size_t``.
Note
You can also specify a C name (
cname
) or the current enumeration. This C name may be used to name functions related to that specific enumeration, e.g. for debugging purposes. Default C name is the C type (with any sequence of spaces replaced with an underscore). If you want to debug and your C type is quite generic (e.g.int
ordouble
), we recommend you specify a C name.C name must be a valid C identifier.
enum = EnumType(CONSTANT_1=0, CONSTANT_2=1, CONSTANT_3=2, ctype='size_t', cname='MyEnumName')
Example with aliases
When creating an enum, you can give some aliases to specific constants while keeping other constants without aliases. An alias must be a string, and there is currently no string format constraints.
To give an alias to a constant in the EnumType constructor, use the following key-value syntax:
constant_name=(constant_alias, constant_value)
You can then retrieve a constant from an alias with method
EnumType.fromalias()
.Aliases are intended to be used in Python code only (only constants names are available in C code). Especially, an alias will be recognized by
Enumtype.filter()
method with non-strict filtering, allowing a maximum flexibility for converting strings to numeric constants available in Python and C code.from theano.graph.type import EnumType # You can remark that constant 'C' does not have an alias. enum = EnumType(A=('alpha', 1), B=('beta', 2), C=3, D=('delta', 4)) # Constants are all directly available by name. print(enum.A, enum.B, enum.C, enum.D) # But we can also now get some constants by alias. a = enum.fromalias('alpha') b = enum.fromalias('beta') d = enum.fromalias('delta') # If method fromalias() receives an unknown alias, # it will looks for a constant with this alias # as exact constant name. c = enum.fromalias('C') # will get enum.C # An alias defined in an EnumType will be correctly converted with non-strict filtering. value = enum.filter('delta', strict=False) # value now contaisn enum.D, ie. 4.
Note
This Type (and subclasses) is not complete and should never be used for regular graph operations.
-
c_cleanup
(name, sub)[source]¶ Return C code to clean up after CLinkerType.c_extract.
This returns C code that should deallocate whatever CLinkerType.c_extract allocated or decrease the reference counts. Do not decrease
py_%(name)s
’s reference count.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
c_code_cache_version
()[source]¶ Return a tuple of integers indicating the version of this type.
An empty tuple indicates an ‘unversioned’ type that will not be cached between processes.
The cache mechanism may erase cached modules that have been superceded by newer versions. See ModuleCache for details.
-
c_declare
(name, sub, check_input=True)[source]¶ Return C code to declare variables that will be instantiated by CLinkerType.c_extract.
Parameters: - name (str) – The name of the
PyObject *
pointer that will the value for this Type - sub (dict string -> string) – a dictionary of special codes. Most importantly
sub[‘fail’]. See CLinker for more info on sub and
fail
.
Notes
It is important to include the name inside of variables which are declared here, so that name collisions do not occur in the source file that is generated.
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted to create class variables for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable declaration fail? Is it even allowed to?
Examples
- name (str) – The name of the
-
c_extract
(name, sub, check_input=True, **kwargs)[source]¶ Return C code to extract a
PyObject *
instance.The code returned from this function must be templated using
%(name)s
, representing the name that the caller wants to call this Variable. The Python objectself.data
is in a variable called"py_%(name)s"
and this code must set the variables declared by c_declare to something representative ofpy_%(name)``s. If the data is improper, set an appropriate exception and insert ``"%(fail)s"
.TODO: Point out that template filling (via sub) is now performed by this function. –jpt
Parameters: - name (str) – The name of the
PyObject *
pointer that will store the value for this type. - sub (dict string -> string) – A dictionary of special codes. Most importantly
sub['fail']
. See CLinker for more info onsub
andfail
.
Examples
- name (str) – The name of the
-
c_init
(name, sub)[source]¶ Return C code to initialize the variables that were declared by CLinkerType.c_declare.
Notes
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted in a class constructor for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable initialization fail? Is it even allowed to?
Examples
-
c_support_code
(**kwargs)[source]¶ Return utility code for use by a Variable or Op.
This is included at global scope prior to the rest of the code for this class.
Question: How many times will this support code be emitted for a graph with many instances of the same type?
Return type: str
-
c_sync
(name, sub)[source]¶ Return C code to pack C types back into a
PyObject
.The code returned from this function must be templated using
"%(name)s"
, representing the name that the caller wants to call this Variable. The returned code may set"py_%(name)s"
to aPyObject*
and thatPyObject*
will be accessible from Python viavariable.data
. Do not forget to adjust reference counts if"py_%(name)s"
is changed from its original value.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
c_to_string
()[source]¶ Return code for a C function that will convert an enumeration value to a string representation. The function prototype is:
int theano_enum_to_string_<cname>(<ctype> value, char* output_string);
Where
ctype
andcname
are the C type and the C name of current Theano enumeration.output_string
should be large enough to contain the longest name in this enumeration.If given value is unknown, the C function sets a Python ValueError exception and returns a non-zero.
This C function may be useful to retrieve some runtime informations. It is available in C code when theano flag
config.cmodule__debug
is set toTrue
.
-
filter
(data, strict=False, allow_downcast=None)[source]¶ Return data or an appropriately wrapped/converted data.
Subclass implementations should raise a TypeError exception if the data is not of an acceptable type.
Parameters: - data (array-like) – The data to be filtered/converted.
- strict (bool (optional)) – If
True
, the data returned must be the same as the data passed as an argument. - allow_downcast (bool (optional)) – If strict is
False
, and allow_downcast isTrue
, the data may be cast to an appropriate type. If allow_downcast isFalse
, it may only be up-cast and not lose precision. If allow_downcast isNone
(default), the behaviour can be type-dependent, but for now it means only Python floats can be down-casted, and only to floatX scalars.
-
fromalias
(alias)[source]¶ Get a constant value by its alias. If there is not such alias in this enum, look for a constant with this alias as constant name.
-
values_eq
(a, b)[source]¶ Return
True
if a and b can be considered exactly equal.a and b are assumed to be valid values of this Type.
-
values_eq_approx
(a, b)[source]¶ Return
True
if a and b can be considered approximately equal.This function is used by Theano debugging tools to decide whether two values are equivalent, admitting a certain amount of numerical instability. For example, for floating-point numbers this function should be an approximate comparison.
By default, this does an exact comparison.
Parameters: - a (array-like) – A potential value for a Variable of this Type.
- b (array-like) – A potential value for a Variable of this Type.
Return type: bool
-
class
theano.graph.type.
Generic
[source]¶ Represents a generic Python object.
This class implements the CType and CLinkerType interfaces for generic PyObject instances.
EXAMPLE of what this means, or when you would use this type.
WRITEME
-
c_cleanup
(name, sub)[source]¶ Return C code to clean up after CLinkerType.c_extract.
This returns C code that should deallocate whatever CLinkerType.c_extract allocated or decrease the reference counts. Do not decrease
py_%(name)s
’s reference count.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
c_code_cache_version
()[source]¶ Return a tuple of integers indicating the version of this type.
An empty tuple indicates an ‘unversioned’ type that will not be cached between processes.
The cache mechanism may erase cached modules that have been superceded by newer versions. See ModuleCache for details.
-
c_declare
(name, sub, check_input=True)[source]¶ Return C code to declare variables that will be instantiated by CLinkerType.c_extract.
Parameters: - name (str) – The name of the
PyObject *
pointer that will the value for this Type - sub (dict string -> string) – a dictionary of special codes. Most importantly
sub[‘fail’]. See CLinker for more info on sub and
fail
.
Notes
It is important to include the name inside of variables which are declared here, so that name collisions do not occur in the source file that is generated.
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted to create class variables for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable declaration fail? Is it even allowed to?
Examples
- name (str) – The name of the
-
c_extract
(name, sub, check_input=True, **kwargs)[source]¶ Return C code to extract a
PyObject *
instance.The code returned from this function must be templated using
%(name)s
, representing the name that the caller wants to call this Variable. The Python objectself.data
is in a variable called"py_%(name)s"
and this code must set the variables declared by c_declare to something representative ofpy_%(name)``s. If the data is improper, set an appropriate exception and insert ``"%(fail)s"
.TODO: Point out that template filling (via sub) is now performed by this function. –jpt
Parameters: - name (str) – The name of the
PyObject *
pointer that will store the value for this type. - sub (dict string -> string) – A dictionary of special codes. Most importantly
sub['fail']
. See CLinker for more info onsub
andfail
.
Examples
- name (str) – The name of the
-
c_init
(name, sub)[source]¶ Return C code to initialize the variables that were declared by CLinkerType.c_declare.
Notes
The variable called
name
is not necessarily defined yet where this code is inserted. This code might be inserted in a class constructor for example, whereas the variablename
might only exist inside certain functions in that class.TODO: Why should variable initialization fail? Is it even allowed to?
Examples
-
c_sync
(name, sub)[source]¶ Return C code to pack C types back into a
PyObject
.The code returned from this function must be templated using
"%(name)s"
, representing the name that the caller wants to call this Variable. The returned code may set"py_%(name)s"
to aPyObject*
and thatPyObject*
will be accessible from Python viavariable.data
. Do not forget to adjust reference counts if"py_%(name)s"
is changed from its original value.Parameters: - name (str) – WRITEME
- sub (dict of str) – WRITEME
-
filter
(data, strict=False, allow_downcast=None)[source]¶ Return data or an appropriately wrapped/converted data.
Subclass implementations should raise a TypeError exception if the data is not of an acceptable type.
Parameters: - data (array-like) – The data to be filtered/converted.
- strict (bool (optional)) – If
True
, the data returned must be the same as the data passed as an argument. - allow_downcast (bool (optional)) – If strict is
False
, and allow_downcast isTrue
, the data may be cast to an appropriate type. If allow_downcast isFalse
, it may only be up-cast and not lose precision. If allow_downcast isNone
(default), the behaviour can be type-dependent, but for now it means only Python floats can be down-casted, and only to floatX scalars.
-
-
class
theano.graph.type.
Type
[source]¶ Interface specification for variable type instances.
A Type instance is mainly responsible for two things:
- creating Variable instances (conventionally, __call__ does this), and
- filtering a value assigned to a Variable so that the value conforms to restrictions imposed by the type (also known as casting, this is done by filter).
-
class
Constant
(type, data, name=None)[source]¶ A Variable with a fixed value field.
Constant nodes make numerous optimizations possible (e.g. constant inlining in C code, constant folding, etc.)
Notes
The data field is filtered by what is provided in the constructor for the Constant’s type field.
-
clone
()[source]¶ We clone this object, but we don’t clone the data to lower memory requirement. We suppose that the data will never change.
-
get_test_value
()[source]¶ Get the test value.
Raises: TestValueError –
-
-
class
Variable
(type, owner=None, index=None, name=None)[source]¶ A Variable is a node in an expression graph that represents a variable.
The inputs and outputs of every Apply (theano.graph.basic.Apply) are Variable instances. The input and output arguments to create a function are also Variable instances. A Variable is like a strongly-typed variable in some other languages; each Variable contains a reference to a Type instance that defines the kind of value the Variable can take in a computation.
A Variable is a container for four important attributes:
type
a Type instance defining the kind of value this Variable can have,owner
either None (for graph roots) or the Apply instance of which self is an output,index
the integer such thatowner.outputs[index] is this_variable
(ignored if owner is None),name
a string to use in pretty-printing and debugging.
There are a few kinds of Variable`s to be aware of: A `Variable which is the output of a symbolic computation has a reference to the Apply instance to which it belongs (property: owner) and the position of itself in the owner’s output list (property: index).
- Variable (this base type) is typically the output of a symbolic computation.
- Constant: a subclass which adds a default and un-replaceable
value
, and requires that owner is None. - TensorVariable subclass of Variable that represents a numpy.ndarray
- object.
- TensorSharedVariable: a shared version of TensorVariable.
- SparseVariable: a subclass of Variable that represents a scipy.sparse.{csc,csr}_matrix object.
- GpuArrayVariable: a subclass of Variable that represents our object on the GPU that is a subset of numpy.ndarray.
- RandomVariable.
A Variable which is the output of a symbolic computation will have an owner not equal to None.
Using the Variables’ owner field and the Apply nodes’ inputs fields, one can navigate a graph from an output all the way to the inputs. The opposite direction is possible with a FunctionGraph and its FunctionGraph.clients dict, which maps `Variable`s to a list of their clients.
Parameters: - type (a Type instance) – The type governs the kind of data that can be associated with this variable.
- owner (None or Apply instance) – The Apply instance which computes the value for this variable.
- index (None or int) – The position of this Variable in owner.outputs.
- name (None or str) – A string for pretty-printing and debugging.
Examples
import theano import theano.tensor as tt a = tt.constant(1.5) # declare a symbolic constant b = tt.fscalar() # declare a symbolic floating-point scalar c = a + b # create a simple expression f = theano.function([b], [c]) # this works because a has a value associated with it already assert 4.0 == f(2.5) # bind 2.5 to an internal copy of b and evaluate an internal c theano.function([a], [c]) # compilation error because b (required by c) is undefined theano.function([a,b], [c]) # compilation error because a is constant, it can't be an input d = tt.value(1.5) # create a value similar to the constant 'a' e = d + b theano.function([d,b], [e]) # this works. d's default value of 1.5 is ignored.
The python variables
a,b,c
all refer to instances of type Variable. The Variable referred to by a is also an instance of Constant.-
clone
()[source]¶ Return a new Variable like self.
Returns: A new Variable instance (or subclass instance) with no owner or index. Return type: Variable instance Notes
Tags are copied to the returned instance.
Name is copied to the returned instance.
-
eval
(inputs_to_values=None)[source]¶ Evaluates this variable.
Parameters: inputs_to_values – A dictionary mapping theano Variables to values. Examples
>>> import numpy as np >>> import theano.tensor as tt >>> x = tt.dscalar('x') >>> y = tt.dscalar('y') >>> z = x + y >>> np.allclose(z.eval({x : 16.3, y : 12.1}), 28.4) True
We passed
eval()
a dictionary mapping symbolic theano variables to the values to substitute for them, and it returned the numerical value of the expression.Notes
eval will be slow the first time you call it on a variable – it needs to call
function()
to compile the expression behind the scenes. Subsequent calls toeval()
on that same variable will be fast, because the variable caches the compiled function.This way of computing has more overhead than a normal Theano function, so don’t use it too much in real scripts.
-
get_parents
()[source]¶ Return a list of the parents of this node. Should return a copy–i.e., modifying the return value should not modify the graph structure.
-
get_test_value
()[source]¶ Get the test value.
Raises: TestValueError –
-
convert_variable
(var: Union[theano.graph.basic.Variable, theano.graph.type.D]) Optional[theano.graph.basic.Variable] [source]¶ Patch a variable so that its Type will match
self
, if possible.If the variable can’t be converted, this should return None.
The conversion can only happen if the following implication is true for all possible val.
self.is_valid_value(val) => var.type.is_valid_value(val)For the majority of types this means that you can only have non-broadcastable dimensions become broadcastable and not the inverse.
The default is to not convert anything which is always safe.
-
abstract
filter
(data: theano.graph.type.D, strict: bool = False, allow_downcast: Optional[bool] = None) Union[theano.graph.type.D, Any] [source]¶ Return data or an appropriately wrapped/converted data.
Subclass implementations should raise a TypeError exception if the data is not of an acceptable type.
Parameters: - data (array-like) – The data to be filtered/converted.
- strict (bool (optional)) – If
True
, the data returned must be the same as the data passed as an argument. - allow_downcast (bool (optional)) – If strict is
False
, and allow_downcast isTrue
, the data may be cast to an appropriate type. If allow_downcast isFalse
, it may only be up-cast and not lose precision. If allow_downcast isNone
(default), the behaviour can be type-dependent, but for now it means only Python floats can be down-casted, and only to floatX scalars.
-
filter_inplace
(value: theano.graph.type.D, storage: Any, strict: bool = False, allow_downcast: Optional[bool] = None) NoReturn [source]¶ Return data or an appropriately wrapped/converted data by converting it in-place.
This method allows one to reuse old allocated memory. If this method is implemented, it will be called instead of Type.filter.
As of now, this method is only used when we transfer new data to a shared variable on a GPU.
Parameters: - value (array-like) –
- storage (array-like) – The old value (e.g. the old NumPy array, CudaNdarray, etc.)
- strict (bool) –
- allow_downcast (bool (optional)) –
Raises: NotImplementedError –
-
filter_variable
(other: Union[theano.graph.basic.Variable, theano.graph.type.D], allow_convert: bool = True) theano.graph.basic.Variable [source]¶ Convert a symbolic variable into this Type, if compatible.
For the moment, the only Type`s compatible with one another are `TensorType and GpuArrayType, provided they have the same number of dimensions, same broadcasting pattern, and same dtype.
If Type`s are not compatible, a ``TypeError` should be raised.
-
is_valid_value
(data: theano.graph.type.D) bool [source]¶ Return
True
for any python object that would be a legal value for a Variable of this Type.
-
make_constant
(value: theano.graph.type.D, name: Optional[str] = None) theano.graph.basic.Constant [source]¶ Return a new Constant instance of this Type.
Parameters: - value (array-like) – The constant value.
- name (None or str) – A pretty string for printing and debugging.
-
make_variable
(name: Optional[str] = None) theano.graph.basic.Variable [source]¶ Return a new Variable instance of this Type.
Parameters: name (None or str) – A pretty string for printing and debugging.
-
value_validity_msg
(data: theano.graph.type.D) str [source]¶ Return a message explaining the output of Type.is_valid_value.
-
classmethod
values_eq
(a: Any, b: Any) bool [source]¶ Return
True
if a and b can be considered exactly equal.a and b are assumed to be valid values of this Type.
-
classmethod
values_eq_approx
(a: Any, b: Any)[source]¶ Return
True
if a and b can be considered approximately equal.This function is used by Theano debugging tools to decide whether two values are equivalent, admitting a certain amount of numerical instability. For example, for floating-point numbers this function should be an approximate comparison.
By default, this does an exact comparison.
Parameters: - a (array-like) – A potential value for a Variable of this Type.
- b (array-like) – A potential value for a Variable of this Type.
Return type: bool