desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'.. todo::
WRITEME'
| def __repr__(self):
| return str(self)
|
'An object representing the data type used by this space.
For simple spaces, this will be a dtype string, as used by numpy,
scipy, and theano (e.g. \'float32\').
For data-less spaces like NoneType, this will be some other string.
For composite spaces, this will be a nested tuple of such strings.'
| @property
def dtype(self):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| @dtype.setter
def dtype(self, new_value):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| @dtype.deleter
def dtype(self):
| raise RuntimeError('You may not delete the dtype of a space, though you can set it to None.')
|
'Returns the origin in this space.
Returns
origin : ndarray
An NumPy array, the shape of a single points in this
space, representing the origin.'
| def get_origin(self):
| raise NotImplementedError()
|
'Returns a batch containing `batch_size` copies of the origin.
Parameters
batch_size : int
The number of examples in the batch to be returned.
dtype : WRITEME
The dtype of the batch to be returned. Default = None.
If None, use self.dtype.
Returns
batch : ndarray
A NumPy array in the shape of a batch of `batch_size` poi... | def get_origin_batch(self, batch_size, dtype=None):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| def make_shared_batch(self, batch_size, name=None, dtype=None):
| dtype = self._clean_dtype_arg(dtype)
origin_batch = self.get_origin_batch(batch_size, dtype)
return theano.shared(origin_batch, name=name)
|
'Returns a symbolic variable representing a batch of points
in this space.
Parameters
name : str
Variable name for the returned batch.
dtype : str
Data type for the returned batch.
If omitted (None), self.dtype is used.
batch_size : int
Number of examples in the returned batch.
Returns
batch : TensorVariable, SparseVar... | def make_theano_batch(self, name=None, dtype=None, batch_size=None):
| raise NotImplementedError()
|
'An alias to make_theano_batch'
| def make_batch_theano(self, name=None, dtype=None, batch_size=None):
| return self.make_theano_batch(name=name, dtype=dtype, batch_size=batch_size)
|
'Returns a Python int (not a theano iscalar) representing
the dimensionality of a point in this space.
If you format a batch of examples in this space as a
design matrix (i.e., VectorSpace batch) then the
number of columns will be equal to the total dimension.'
| def get_total_dimension(self):
| raise NotImplementedError((str(type(self)) + ' does not implement get_total_dimension.'))
|
'Returns a numeric batch (e.g. a numpy.ndarray or scipy.sparse sparse
array), formatted to lie in this space.
This is just a wrapper around self._format_as, with an extra check
to throw an exception if <batch> is symbolic.
Should be invertible, i.e. batch should equal
`space.format_as(self.format_as(batch, space), self... | def np_format_as(self, batch, space):
| self._check_is_numeric(batch)
return self._format_as(is_numeric=True, batch=batch, space=space)
|
'Called by self._format_as(space), to check whether self and space
have compatible sizes. Throws a ValueError if they don\'t.'
| def _check_sizes(self, space):
| my_dimension = self.get_total_dimension()
other_dimension = space.get_total_dimension()
if (my_dimension != other_dimension):
raise ValueError(((((((str(self) + ' with total dimension ') + str(my_dimension)) + " can't format a batch into ") + str(space)) + 'because i... |
'.. todo::
WRITEME'
| def format_as(self, batch, space):
| self._check_is_symbolic(batch)
return self._format_as(is_numeric=False, batch=batch, space=space)
|
'The shared implementation of format_as() and np_format_as().
Agnostic to whether batch is symbolic or numeric, which avoids
duplicating a lot of code between format_as() and np_format_as().
Calls the appropriate callbacks, then calls self._format_as_impl().
Should be invertible, i.e. batch should equal
`space._format_... | def _format_as(self, is_numeric, batch, space):
| assert isinstance(is_numeric, bool)
self._validate(is_numeric, batch)
self._check_sizes(space)
return self._format_as_impl(is_numeric, batch, space)
|
'Actual implementation of format_as/np_format_as. Formats batch to
target_space.
Should be invertible, i.e. batch should equal
`space._format_as_impl(self._format_as_impl(batch, space), self)`
Parameters
is_numeric : bool
Set to True to treat batch as a numeric batch, False to
treat it as a symbolic batch. This is nece... | def _format_as_impl(self, is_numeric, batch, target_space):
| raise NotImplementedError(('%s does not implement _format_as_impl().' % type(self)))
|
'Returns a numeric batch (e.g. a numpy.ndarray or scipy.sparse sparse
array), with formatting from space undone.
This is just a wrapper around self._undo_format_as, with an extra check
to throw an exception if <batch> is symbolic.
Parameters
batch : numpy.ndarray, or one of the scipy.sparse matrices.
Array which lies i... | def undo_np_format_as(self, batch, space):
| self._check_is_numeric(batch)
return space.np_format_as(batch=batch, space=self)
|
'Returns a symbolic batch (e.g. a theano.tensor or theano.sparse
array), with formatting from space undone.
This is just a wrapper around self._undo_format_as, with an extra check
to throw an exception if <batch> is symbolic. Formatting to space
Parameters
batch : numpy.ndarray, or one of the scipy.sparse matrices.
Arr... | def undo_format_as(self, batch, space):
| self._check_is_symbolic(batch)
space.validate(batch)
self._check_sizes(space)
batch = self._undo_format_as_impl(batch=batch, space=space)
self.validate(batch)
return batch
|
'Actual implementation of undo_format_as.
Undoes target_space_formatting.
Note that undo_np_format_as calls np_format_as.
Parameters
batch : a theano symbol, or a nested tuple thereof
Implementations of this method may assume that batch lies in
space (i.e. that it passed self._validate(batch) without throwing
an except... | def _undo_format_as_impl(self, batch, target_space):
| raise NotImplementedError(('%s does not implement _undo_format_as_impl().' % type(self)))
|
'Runs all validate_callbacks, then checks that batch lies in this space.
Raises an exception if the batch isn\'t symbolic, or if any of these
checks fails.
Parameters
batch : a symbolic (Theano) variable that lies in this space.'
| def validate(self, batch):
| self._check_is_symbolic(batch)
self._validate(is_numeric=False, batch=batch)
|
'Runs all np_validate_callbacks, then checks that batch lies in this
space. Raises an exception if the batch isn\'t numeric, or if any of
these checks fails.
Parameters
batch : a numeric (numpy/scipy.sparse) variable that lies in this space'
| def np_validate(self, batch):
| self._check_is_numeric(batch)
self._validate(is_numeric=True, batch=batch)
|
'Shared implementation of validate() and np_validate().
Calls validate_callbacks or np_validate_callbacks as appropriate,
then calls self._validate_impl(batch) to verify that batch belongs
to this space.
Parameters
is_numeric : bool.
Set to True to call np_validate_callbacks,
False to call validate_callbacks.
Necessary... | def _validate(self, is_numeric, batch):
| if is_numeric:
self._check_is_numeric(batch)
callbacks_name = 'np_validate_callbacks'
else:
self._check_is_symbolic(batch)
callbacks_name = 'validate_callbacks'
if (not hasattr(self, callbacks_name)):
raise TypeError((('The ' + str(type(self))) + ' Space subc... |
'Subclasses must override this method so that it throws an
exception if the batch is the wrong shape or dtype for this Space.
Parameters
is_numeric : bool
Set to True to treat batch as a numeric type
(numpy.ndarray or scipy.sparse matrix).
Set to False to treat batch as a symbolic (Theano) variable.
Necessary because b... | def _validate_impl(self, is_numeric, batch):
| raise NotImplementedError(('Class "%s" does not implement _validate_impl()' % type(self)))
|
'Returns the batch size of a symbolic batch.
Parameters
batch : WRITEME'
| def batch_size(self, batch):
| return self._batch_size(is_numeric=False, batch=batch)
|
'Returns the batch size of a numeric (numpy/scipy.sparse) batch.
Parameters
batch : WRITEME'
| def np_batch_size(self, batch):
| return self._batch_size(is_numeric=True, batch=batch)
|
'.. todo::
WRITEME'
| def _batch_size(self, is_numeric, batch):
| self._validate(is_numeric, batch)
return self._batch_size_impl(is_numeric, batch)
|
'Returns the batch size of a batch.
Parameters
batch : WRITEME'
| def _batch_size_impl(self, is_numeric, batch):
| raise NotImplementedError(('%s does not implement batch_size' % type(self)))
|
'Returns a batch of data starting from index `start` to index `stop`
Parameters
data : WRITEME
start : WRITEME
end : WRITEME'
| def get_batch(self, data, start, end):
| raise NotImplementedError(((str(type(self)) + ' does not implement ') + 'get_batch'))
|
'.. todo::
WRITEME'
| @staticmethod
def _check_is_numeric(batch):
| if (not is_numeric_batch(batch)):
raise TypeError(('Expected batch to be a numeric variable, but instead it was of type "%s"' % type(batch)))
|
'.. todo::
WRITEME'
| @staticmethod
def _check_is_symbolic(batch):
| if (not is_symbolic_batch(batch)):
raise TypeError(('Expected batch to be a symbolic variable, but instead it was of type "%s"' % type(batch)))
|
'Checks dtype string for validity, and returns it if it is.
If dtype is \'floatX\', returns the theano.config.floatX dtype (this will
either be \'float32\' or \'float64\'.'
| def _clean_dtype_arg(self, dtype):
| if isinstance(dtype, np.dtype):
dtype = str(dtype)
if (dtype == 'floatX'):
return theano.config.floatX
if ((dtype is None) or (dtype in tuple((x.dtype for x in theano.scalar.all_types)))):
return dtype
raise TypeError(('Unrecognized value "%s" (type %s) for dtyp... |
'if dtype is None, checks that self.dtype is not None.
Otherwise, same as superclass\' implementation.'
| def _clean_dtype_arg(self, dtype):
| if (dtype is None):
if (self.dtype is None):
raise TypeError('self.dtype is None, so you must provide a non-None dtype argument to this method.')
return self.dtype
return super(SimplyTypedSpace, self)._clean_dtype_arg(dtype)
|
'.. todo::
WRITEME'
| def _validate_impl(self, is_numeric, batch):
| if isinstance(batch, tuple):
raise TypeError('This space only supports simple dtypes, but received a composite batch.')
def is_complex(dtype):
return np.issubdtype(dtype, np.complex)
def is_integral(dtype):
return np.issubdtype(dtype, np.integer)
if ... |
'.. todo::
WRITEME'
| @property
def dtype(self):
| return self._dtype
|
'.. todo::
WRITEME'
| @dtype.setter
def dtype(self, new_dtype):
| self._dtype = super(SimplyTypedSpace, self)._clean_dtype_arg(new_dtype)
|
'.. todo::
WRITEME'
| def __setstate__(self, state_dict):
| self.__dict__.update(state_dict)
if ('_dtype' not in state_dict):
self._dtype = theano.config.floatX
|
'Return a string representation'
| def __str__(self):
| return ('%(classname)s(dim=%(dim)s, max_labels=%(max_labels)s, dtype=%(dtype)s)' % dict(classname=self.__class__.__name__, dim=self.dim, max_labels=self.max_labels, dtype=self.dtype))
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return ((type(self) == type(other)) and (self.max_labels == other.max_labels) and (self.dim == other.dim) and (self.dtype == other.dtype))
|
'.. todo::
WRITEME'
| def __ne__(self, other):
| return (not (self == other))
|
'.. todo::
WRITEME'
| @functools.wraps(Space._validate_impl)
def _validate_impl(self, is_numeric, batch):
| super(IndexSpace, self)._validate_impl(is_numeric, batch)
if is_numeric:
if ((not isinstance(batch, np.ndarray)) and (str(type(batch)) != "<type 'CudaNdarray'>")):
raise TypeError(('The value of a IndexSpace batch should be a numpy.ndarray, or CudaNdarray,... |
'.. todo::
WRITEME'
| def __str__(self):
| return ('%s(dim=%d%s, dtype=%s)' % (self.__class__.__name__, self.dim, (', sparse' if self.sparse else ''), self.dtype))
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return ((type(self) == type(other)) and (self.dim == other.dim) and (self.sparse == other.sparse) and (self.dtype == other.dtype))
|
'.. todo::
WRITEME'
| def __hash__(self):
| return hash((type(self), self.dim, self.sparse, self.dtype))
|
'.. todo::
WRITEME'
| @functools.wraps(Space._validate_impl)
def _validate_impl(self, is_numeric, batch):
| super(VectorSpace, self)._validate_impl(is_numeric, batch)
if isinstance(batch, theano.gof.Variable):
if self.sparse:
if (not isinstance(batch.type, theano.sparse.SparseType)):
raise TypeError(('This VectorSpace is%s sparse, but the provided batch is ... |
'Return a string representation'
| def __str__(self):
| return ('%(classname)s(dim=%(dim)s, dtype=%(dtype)s)' % dict(classname=self.__class__.__name__, dim=self.dim, dtype=self.dtype))
|
'Return a string representation'
| def __str__(self):
| return ('%(classname)s(dim=%(dim)s, max_labels=%(max_labels)s, dtype=%(dtype)s)' % dict(classname=self.__class__.__name__, dim=self.dim, max_labels=self.max_labels, dtype=self.dtype))
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return ((type(self) == type(other)) and (self.max_labels == other.max_labels) and (self.dim == other.dim) and (self.dtype == other.dtype))
|
'.. todo::
WRITEME'
| def __str__(self):
| return ('%s(shape=%s, num_channels=%d, axes=%s, dtype=%s)' % (self.__class__.__name__, str(self.shape), self.num_channels, str(self.axes), self.dtype))
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| assert isinstance(self.axes, tuple)
if isinstance(other, Conv2DSpace):
assert isinstance(other.axes, tuple)
return ((type(self) == type(other)) and (self.shape == other.shape) and (self.num_channels == other.num_channels) and (self.axes == other.axes) and (self.dtype == other.dtype))
|
'.. todo::
WRITEME'
| def __hash__(self):
| return hash((type(self), self.shape, self.num_channels, self.axes, self.dtype))
|
'Returns a view of tensor using the axis semantics defined
by dst_axes. (If src_axes matches dst_axes, returns
tensor itself)
Useful for transferring tensors between different
Conv2DSpaces.
Parameters
tensor : tensor_like
A 4-tensor representing a batch of images
src_axes : WRITEME
Axis semantics of tensor
dst_axes : W... | @staticmethod
def convert(tensor, src_axes, dst_axes):
| src_axes = tuple(src_axes)
dst_axes = tuple(dst_axes)
assert (len(src_axes) == 4)
assert (len(dst_axes) == 4)
if (src_axes == dst_axes):
return tensor
shuffle = [src_axes.index(elem) for elem in dst_axes]
if is_symbolic_batch(tensor):
return tensor.dimshuffle(*shuffle)
el... |
'.. todo::
WRITEME'
| @staticmethod
def convert_numpy(tensor, src_axes, dst_axes):
| return Conv2DSpace.convert(tensor, src_axes, dst_axes)
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return ((type(self) == type(other)) and (len(self.components) == len(other.components)) and all(((my_component == other_component) for (my_component, other_component) in zip(self.components, other.components))))
|
'.. todo::
WRITEME'
| def __hash__(self):
| return hash((type(self), tuple(self.components)))
|
'.. todo::
WRITEME'
| def __str__(self):
| return ('%(classname)s(%(components)s)' % dict(classname=self.__class__.__name__, components=', '.join([str(c) for c in self.components])))
|
'Returns a nested tuple of dtype strings. NullSpaces will yield a bogus
dtype string (see NullSpace.dtype).'
| @property
def dtype(self):
| def get_dtype_of_space(space):
if isinstance(space, CompositeSpace):
return tuple((get_dtype_of_space(c) for c in space.components))
elif isinstance(space, NullSpace):
return NullSpace().dtype
else:
return space.dtype
return get_dtype_of_space(self)
|
'If new_dtype is None or a string, it will be applied to all components
(except any NullSpaces).
If new_dtype is a (nested) tuple, its elements will be applied to
corresponding components.'
| @dtype.setter
def dtype(self, new_dtype):
| if isinstance(new_dtype, tuple):
for (component, new_dt) in safe_zip(self.components, new_dtype):
component.dtype = new_dt
elif ((new_dtype is None) or isinstance(new_dtype, str)):
for component in self.components:
if (not isinstance(component, NullSpace)):
... |
'Returns a new Space containing only the components whose indices
are given in subset.
The new space will contain the components in the order given in the
subset list.
Parameters
subset : WRITEME
Notes
The returned Space may not be a CompositeSpace if `subset` contains
only one index.'
| def restrict(self, subset):
| assert isinstance(subset, (list, tuple))
if (len(subset) == 1):
(idx,) = subset
return self.components[idx]
return CompositeSpace([self.components[i] for i in subset])
|
'Returns a batch containing only the components whose indices are
present in subset.
May not be a tuple anymore if there is only one index.
Outputs will be ordered in the order that they appear in subset.
Only supports symbolic batches.
Parameters
batch : WRITEME
subset : WRITEME'
| def restrict_batch(self, batch, subset):
| self._validate(is_numeric=False, batch=batch)
assert isinstance(subset, (list, tuple))
if (len(subset) == 1):
(idx,) = subset
return batch[idx]
return tuple([batch[i] for i in subset])
|
'Supports formatting to a single VectorSpace, or to a CompositeSpace.
CompositeSpace->VectorSpace:
Traverses the nested components in depth-first order, serializing the
leaf nodes (i.e. the non-composite subspaces) into the VectorSpace.
CompositeSpace->CompositeSpace:
Only works for two CompositeSpaces that have the sa... | @functools.wraps(Space._format_as_impl)
def _format_as_impl(self, is_numeric, batch, space):
| if isinstance(space, VectorSpace):
pieces = []
for (component, input_piece) in zip(self.components, batch):
subspace = VectorSpace(dim=component.get_total_dimension(), dtype=space.dtype, sparse=space.sparse)
pieces.append(component._format_as(is_numeric, input_piece, subspace... |
'Undoes the formatting to a single VectorSpace, or to a CompositeSpace.
CompositeSpace->VectorSpace:
Traverses the nested components in depth-first order, serializing the
leaf nodes (i.e. the non-composite subspaces) into the VectorSpace.
CompositeSpace->CompositeSpace:
Only works for two CompositeSpaces that have the ... | @functools.wraps(Space._undo_format_as_impl)
def _undo_format_as_impl(self, batch, space):
| if isinstance(space, VectorSpace):
if space.sparse:
owner = batch.owner
assert (owner is not None)
assert ('HStack' in str(owner.op))
batch = owner.inputs
else:
owner = batch.owner
assert (owner is not None)
assert (... |
'Calls get_origin_batch on all subspaces, and returns a (nested)
tuple containing their return values.
Parameters
batch_size : int
Batch size.
dtype : str
the dtype to use for all the get_origin_batch() calls on
subspaces. If dtype is None, or a single dtype string, that will
be used for all calls. If dtype is a (neste... | def get_origin_batch(self, batch_size, dtype=None):
| dtype = self._clean_dtype_arg(dtype)
return tuple((component.get_origin_batch(batch_size, dt) for (component, dt) in safe_zip(self.components, dtype)))
|
'Calls make_theano_batch on all subspaces, and returns a (nested)
tuple containing their return values.
Parameters
name : str
Name of the symbolic variable
dtype : str
The dtype of the returned batch.
If dtype is a string, it will be applied to all components.
If dtype is None, C.dtype will be used for each component C... | @functools.wraps(Space.make_theano_batch)
def make_theano_batch(self, name=None, dtype=None, batch_size=None):
| if (name is None):
name = ([None] * len(self.components))
elif (not isinstance(name, (list, tuple))):
name = [('%s[%i]' % (name, i)) for i in xrange(len(self.components))]
dtype = self._clean_dtype_arg(dtype)
assert isinstance(name, (list, tuple))
assert isinstance(dtype, (list, tupl... |
'If dtype is None or a string, this returns a nested tuple that mirrors
the tree structure of this CompositeSpace, with dtype at the leaves.
If dtype is a nested tuple, this checks that it has the same tree
structure as this CompositeSpace.'
| def _clean_dtype_arg(self, dtype):
| super_self = super(CompositeSpace, self)
def make_dtype_tree(dtype, space):
'\n Creates a nested tuple tree that mirrors the tree structure of\n <space>, populating the le... |
'.. todo::
WRITEME'
| def __str__(self):
| return 'NullSpace'
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return (type(self) == type(other))
|
'.. todo::
WRITEME'
| def __hash__(self):
| return hash(type(self))
|
'.. todo::
WRITEME'
| @property
def dtype(self):
| return ("%s's dtype" % self.__class__.__name__)
|
'.. todo::
WRITEME'
| @dtype.setter
def dtype(self, new_dtype):
| if (new_dtype != self.dtype):
raise TypeError(('%s can only take the bogus dtype "%s"' % (self.__class__.__name__, self.dtype)))
|
'.. todo::
WRITEME'
| def minimize(self, *inputs):
| if self.verbose:
logger.info('minimizing')
alpha_list = list(self.init_alpha)
orig_obj = self.obj(*inputs)
if self.verbose:
logger.info(orig_obj)
iters = 0
if self.reset_conjugate:
norm = 0.0
else:
norm = 1.0
while (iters != self.max_iter):
if self... |
'.. todo::
WRITEME'
| def _true_inputs(self, inputs):
| return [elem for (elem, shared) in safe_zip(inputs, self._shared_mask) if (not shared)]
|
'.. todo::
WRITEME'
| def _shared_inputs(self, inputs):
| return [elem for (elem, shared) in safe_zip(inputs, self._shared_mask) if shared]
|
'.. todo::
WRITEME'
| def _set_shared(self, inputs):
| for (elem, mask, shared) in safe_zip(inputs, self._shared_mask, self._shared):
if mask:
shared.set_value(elem)
|
'.. todo::
WRITEME'
| def __call__(self, *batches):
| for batch in batches:
if (not isinstance(batch, list)):
raise TypeError(((('Expected each argument to be a list, but one argument is ' + str(batch)) + ' of type ') + str(type(batch))))
total_examples = np.cast[config.floatX](sum([batch[0].shape[0] fo... |
'Temporary method to manage the deprecation'
| def __new__(cls, filename, X=None, topo_view=None, y=None, load_all=False, cache_size=None, sources=None, spaces=None, aliases=None, use_h5py='auto', **kwargs):
| if ((X is not None) or (topo_view is not None)):
warnings.warn('A dataset is using the old interface that is now deprecated and will become officially unsupported as of July 27, 2015. The dataset should use the new interface ... |
'Class constructor'
| def __init__(self, filename, sources, spaces, aliases=None, load_all=False, cache_size=None, use_h5py='auto', **kwargs):
| assert isinstance(filename, string_types)
assert isfile(filename), ('%s does not exist.' % filename)
assert isinstance(sources, list)
assert all([isinstance(el, string_types) for el in sources])
assert isinstance(spaces, list)
assert all([isinstance(el, Space) for el in spaces])
ass... |
'Loads elements from an HDF5 dataset using either h5py or tables. It can
load either the whole object in memory or a reference to the object on
disk, depending on the load_all parameter. Returns a list of objects.
Parameters
sources : list of str
List of HDF5 keys corresponding to the data to be loaded.
load_all : bool... | def _read_hdf5(self, sources, aliases, load_all=False, use_h5py=True):
| data = alias_dict()
if use_h5py:
for (s, a) in safe_zip(sources, aliases):
if load_all:
data[(s, a)] = self._fhandler[s][:]
else:
data[(s, a)] = self._fhandler[s]
data[s].ndim = len(data[s].shape)
else:
for (s, a) in saf... |
'if data_specs is set to None, the aliases (or sources) and spaces
provided when the dataset object has been created will be used.'
| @wraps(Dataset.iterator, assigned=(), updated=(), append=True)
def iterator(self, mode=None, data_specs=None, batch_size=None, num_batches=None, rng=None, return_tuple=False, **kwargs):
| if (data_specs is None):
data_specs = (self._get_sources, self._get_spaces)
[mode, batch_size, num_batches, rng, data_specs] = self._init_iterator(mode, batch_size, num_batches, rng, data_specs)
convert = None
return FiniteDatasetIterator(self, mode(self.get_num_examples(), batch_size, num_batch... |
'Returns the aliases (if defined, sources otherwise) provided when the
HDF5 object was created
Returns
A string or a list of strings.'
| def _get_sources(self):
| return tuple([(alias if alias else source) for (alias, source) in safe_zip(self._aliases, self._sources)])
|
'Returns the Space(s) associated with the aliases (or sources) specified
when the HDF5 object has been created.
Returns
A Space or a list of Spaces.'
| def _get_spaces(self):
| space = [self.spaces[s] for s in self._get_sources]
return (space[0] if (len(space) == 1) else tuple(space))
|
'Returns a tuple `(space, source)` for each one of the provided
source_or_alias keys, if any. If no key is provided, it will
use self.aliases, if not None, or self.sources.'
| def get_data_specs(self, source_or_alias=None):
| if (source_or_alias is None):
source_or_alias = self._get_sources()
if isinstance(source_or_alias, (list, tuple)):
space = tuple([self.spaces[s] for s in source_or_alias])
space = CompositeSpace(space)
else:
space = self.spaces[source_or_alias]
return (space, source_or_al... |
'DEPRECATED
Returns all the data, as it is internally stored.
The definition and format of these data are described in
`self.get_data_specs()`.
Returns
data : numpy matrix or 2-tuple of matrices
The data'
| def get_data(self):
| return tuple([self.data[s] for s in self._get_sources()])
|
'Retrieves the requested elements from the dataset.
Parameter
sources : tuple
A tuple of source identifiers
indexes : slice or list
A slice or a list of indexes
Return
rval : tuple
A tuple of batches, one for each source'
| def get(self, sources, indexes):
| assert (isinstance(sources, (tuple, list)) and (len(sources) > 0)), 'sources should be an instance of tuple and not empty'
assert all([isinstance(el, string_types) for el in sources]), 'sources elements should be strings'
assert isinstance(indexes, (tuple, list, slice,... |
'Return the number of examples *OF THE FIRST SOURCE*.
Note that this behavior will probably be deprecated in the future,
returing a list of num_examples. Do not rely on this function unless
unavoidable.
Parameter
source_or_alias : str, optional
The source you want the number of examples of'
| @wraps(Dataset.get_num_examples, assigned=(), updated=())
def get_num_examples(self, source_or_alias=None):
| assert ((source_or_alias is None) or isinstance(source_or_alias, string_types))
if (source_or_alias is None):
alias = self._get_sources()
alias = (alias[0] if isinstance(alias, (list, tuple)) else alias)
data = self.data[alias]
else:
data = self.data[source_or_alias]
retu... |
'Returns the item corresponding to a key or an alias.
Parameter
key_or_alias: any valid key for a dictionary
A key or an alias.'
| def __getitem__(self, key_or_alias):
| assert isinstance(key_or_alias, string_types)
try:
return super(alias_dict, self).__getitem__(key_or_alias)
except KeyError:
return super(alias_dict, self).__getitem__(self.__a2k__[key_or_alias])
|
'Add an element to the dictionary
Parameter
keys: either a tuple `(key, alias)` or any valid key for a dictionary
The key and optionally the alias of the new element.
value: any input accepted as value by a dictionary
The value of the new element.i
Notes
You can add elements to the dictionary as follows:
1) my_dict[key... | def __setitem__(self, keys, value):
| assert isinstance(keys, (list, tuple, string_types))
if isinstance(keys, (list, tuple)):
assert all([((el is None) or isinstance(el, string_types)) for el in keys])
if isinstance(keys, (list, tuple)):
if (keys[1] is not None):
if ((keys[0] in self.__a2k__) or (keys[0] in super(al... |
'Add an alias to a key of the dictionary that doesn\'t have already an
alias.
Parameter
keys: any valid key for a dictionary
A key of the dictionary.
alias: any input accepted as key by a dictionary
The alias.'
| def set_alias(self, key, alias):
| if (alias is None):
return
if (key not in super(alias_dict, self).keys()):
raise NameError('The key is not in the dictionary')
if ((key in self.__k2a__) and (alias != self.__k2a__[key])):
raise NameError('The key is already associated to a diffe... |
'Returns true if the key or alias is an element of the dictionary
Parameter
keys_or_alias: any valid key for a dictionary
The key or the alias to look for.'
| def __contains__(self, key_or_alias):
| try:
isalias = super(alias_dict, self).__contains__(self.__k2a__[key_or_alias])
except KeyError:
isalias = False
pass
return (isalias or super(alias_dict, self).__contains__(key_or_alias))
|
'.. todo::
WRITEME'
| def __init__(self, preprocessor=None):
| self.class_names = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
lines = iris_data.split('\n')
X = []
y = []
for line in lines:
row = line.split(',')
X.append([float(elem) for elem in row[:(-1)]])
y.append(self.class_names.index(row[(-1)]))
X = np.array(X)
asse... |
'Reads the specified NORB dataset from a memmap cache.
Creates this cache first, if necessary.
Parameters
which_norb : str
Valid values: \'big\' or \'small\'.
Chooses between the (big) \'NORB dataset\', and the \'Small NORB
dataset\'.
which_set : str
Valid values: \'test\', \'train\', or \'both\'.
Chooses between the t... | def __init__(self, which_norb, which_set, image_dtype='uint8'):
| if (which_norb not in ('big', 'small')):
raise ValueError(("Expected which_norb argument to be either 'big' or 'small', not '%s'" % str(which_norb)))
if (which_set not in ('test', 'train', 'both')):
raise ValueError(("Expected which_set argument to be ... |
'Return a topological view.
Parameters
mat : ndarray
A design matrix of images, one per row.
single_tensor : bool
If True, returns a single tensor. If False, returns separate
tensors for the left and right stereo images.
returns : ndarray, tuple
If single_tensor is True, returns ndarray.
Else, returns the tuple (left_i... | @functools.wraps(DenseDesignMatrix.get_topological_view)
def get_topological_view(self, mat=None, single_tensor=False):
| result = super(NORB, self).get_topological_view(mat)
if single_tensor:
if ('s' not in self.view_converter.axes):
raise ValueError(('self.view_converter.axes must contain "s" (stereo image index) in order to split the images into left and right ... |
'Support method for pickling. Returns the complete state of this object
as a dictionary, which is then pickled.
This state does not include the memmaps\' contents. Rather, it includes
enough info to find the memmap and re-load it from disk in the same
state.
Note that pickling a NORB will set its memmaps (self.X and se... | def __getstate__(self):
| _check_pickling_support()
result = copy.copy(self.__dict__)
assert isinstance(self.X, numpy.memmap), ('Expected X to be a memmap, but it was a %s.' % str(type(self.X)))
assert isinstance(self.y, numpy.memmap), ('Expected y to be a memmap, but it was ... |
'Support method for unpickling. Takes a \'state\' dictionary and
interprets it in order to set this object\'s fields.'
| def __setstate__(self, state):
| _check_pickling_support()
X_info = state['X_info']
y_info = state['y_info']
del state['X_info']
del state['y_info']
self.__dict__.update(state)
def load_memmap_from_info(info):
data_dir = string_utils.preprocess('${PYLEARN2_DATA_PATH}')
info['filename'] = os.path.join(data_di... |
'The arguments describe how the data is laid out in the design matrix.
Parameters
shape : tuple
A tuple of 4 ints, describing the shape of each datum.
This is the size of each axis in <axes>, excluding the \'b\' axis.
axes : tuple
A tuple of the following elements in any order:
\'b\' batch axis
\'s\' stereo axis
0 ... | def __init__(self, shape, axes=None):
| shape = tuple(shape)
if (not all((isinstance(s, int) for s in shape))):
raise TypeError('Shape must be a tuple/list of ints')
if (len(shape) != 4):
raise ValueError(('Shape array needs to be of length 4, got %s.' % shape))
datum_axes = list(ax... |
'Returns a batch formatted to a space.
Parameters
batch : ndarray
The batch to format
space : a pylearn2.space.Space
The target space to format to.'
| def get_formatted_batch(self, batch, space):
| return self.storage_space.np_format_as(batch, space)
|
'Called by DenseDesignMatrix.get_formatted_view(), get_batch_topo()
Parameters
design_mat : ndarray'
| def design_mat_to_topo_view(self, design_mat):
| return self.storage_space.np_format_as(design_mat, self.topo_space)
|
'Called by DenseDesignMatrix.get_weights_view()
Parameters
design_mat : ndarray'
| def design_mat_to_weights_view(self, design_mat):
| return self.design_mat_to_topo_view(design_mat)
|
'Used by DenseDesignMatrix.set_topological_view(), .get_design_mat()
Parameters
topo_batch : ndarray'
| def topo_view_to_design_mat(self, topo_batch):
| return self.topo_space.np_format_as(topo_batch, self.storage_space)
|
'TODO: write documentation.'
| def view_shape(self):
| return self.shape
|
'TODO: write documentation.'
| def weights_view_shape(self):
| return self.view_shape()
|
'Change the order of the axes.
Parameters
axes : tuple
Must have length 5, must contain \'b\', \'s\', 0, 1, \'c\'.'
| def set_axes(self, axes):
| axes = tuple(axes)
if (len(axes) != 5):
raise ValueError(('Axes must have 5 elements; got %s' % str(axes)))
for required_axis in ('b', 's', 0, 1, 'c'):
if (required_axis not in axes):
raise ValueError(("Axes must contain 'b', 's', 0, 1, and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.