desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get a handle for an HDF5 dataset, or load the entire dataset into
memory.
Parameters
dataset : str
Name or path of HDF5 dataset.
load_all : bool, optional (default False)
If true, load dataset into memory.'
| def get_dataset(self, dataset, load_all=False):
| if load_all:
data = self._file[dataset][:]
else:
data = self._file[dataset]
data.ndim = len(data.shape)
return data
|
'Get an iterator for this dataset.
The FiniteDatasetIterator uses indexing that is not supported by
HDF5 datasets, so we change the class to HDF5DatasetIterator to
override the iterator.next method used in dataset iteration.
Parameters
WRITEME'
| def iterator(self, *args, **kwargs):
| iterator = super(HDF5DatasetDeprecated, self).iterator(*args, **kwargs)
iterator.__class__ = HDF5DatasetIterator
return iterator
|
'Set up dataset topological view, without building an in-memory
design matrix.
This is mostly copied from DenseDesignMatrix, except:
* HDF5ViewConverter is used instead of DefaultViewConverter
* Data specs are derived from topo_view, not X
* NaN checks have been moved to HDF5DatasetIterator.next
Note that y may be load... | def set_topological_view(self, V, axes=('b', 0, 1, 'c')):
| shape = [V.shape[axes.index('b')], V.shape[axes.index(0)], V.shape[axes.index(1)], V.shape[axes.index('c')]]
self.view_converter = HDF5ViewConverter(shape[1:], axes=axes)
self.X = self.view_converter.topo_view_to_design_mat(V)
self.X_topo_space = self.view_converter.topo_space
X_space = VectorSpace(... |
'Get the next subset of the dataset during dataset iteration.
Converts index selections for batches to boolean selections that
are supported by HDF5 datasets.'
| def next(self):
| next_index = self._subset_iterator.next()
sel = np.zeros(self.num_examples, dtype=bool)
sel[next_index] = True
next_index = sel
rval = []
for (data, fn) in safe_izip(self._raw_data, self._convert):
try:
this_data = data[next_index]
except TypeError:
if (da... |
'Generate a design matrix from the topological view.
This override of DefaultViewConverter.topo_view_to_design_mat does
not attempt to transpose the topological view, since transposition
is not supported by HDF5 datasets.
Parameters
WRITEME'
| def topo_view_to_design_mat(self, V):
| v_shape = (V.shape[self.axes.index('b')], V.shape[self.axes.index(0)], V.shape[self.axes.index(1)], V.shape[self.axes.index('c')])
if np.any((np.asarray(self.shape) != np.asarray(v_shape[1:]))):
raise ValueError(((('View converter for views of shape batch size followed by '... |
'Indexes the design matrix and transforms the requested batch from
the topological view.
Parameters
item : slice or ndarray
Batch selection. Either a slice or a boolean mask.'
| def __getitem__(self, item):
| sel = ([slice(None)] * len(self.topo_view_shape))
sel[self.axes.index('b')] = item
sel = tuple(sel)
V = self.topo_view[sel]
batch_size = V.shape[self.axes.index('b')]
rval = np.zeros((batch_size, (self.pixels_per_channel * self.n_channels)), dtype=V.dtype)
for i in xrange(self.n_channels):
... |
'Sanity checks for X_labels and y_labels.'
| def _check_labels(self):
| if (self.X_labels is not None):
assert (self.X is not None)
assert (self.view_converter is None)
assert (self.X.ndim <= 2)
assert np.all((self.X < self.X_labels))
if (self.y_labels is not None):
assert (self.y is not None)
assert (self.y.ndim <= 2)
assert ... |
'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):
| if (self.y is None):
return self.X
else:
return (self.X, self.y)
|
'Calling this function changes the serialization behavior of the object
permanently.
If this function has been called, when the object is serialized, it
will save the design matrix to `path` as a .npy file rather
than pickling the design matrix along with the rest of the dataset
object. This avoids pickle\'s unfortunat... | def use_design_loc(self, path):
| if (not path.endswith('.npy')):
raise ValueError("path should end with '.npy'")
self.design_loc = path
|
'The index of the axis of the batches
Returns
axis : int
The axis of a topological view of this dataset that corresponds
to indexing over different examples.'
| def get_topo_batch_axis(self):
| axis = self.view_converter.axes.index('b')
return axis
|
'If called, when pickled the dataset will be saved using only
8 bits per element.
.. todo::
Not sure this should be implemented as something a base dataset
does. Perhaps as a mixin that specific datasets (i.e. CIFAR10)
inherit from.'
| def enable_compression(self):
| self.compress = True
|
'.. todo::
WRITEME'
| def __getstate__(self):
| rval = copy.copy(self.__dict__)
if self.compress:
rval['compress_min'] = rval['X'].min(axis=0)
rval['X'] = (rval['X'] - rval['compress_min'])
rval['compress_max'] = rval['X'].max(axis=0)
rval['compress_max'][(rval['compress_max'] == 0)] = 1
rval['X'] *= (255.0 / rval['com... |
'.. todo::
WRITEME'
| def __setstate__(self, d):
| if (d['design_loc'] is not None):
if control.get_load_data():
fname = cache.datasetCache.cache_file(d['design_loc'])
d['X'] = np.load(fname)
else:
d['X'] = None
if d['compress']:
X = d['X']
mx = d['compress_max']
mn = d['compress_min']
... |
'This function splits the dataset according to the number of
train_size if defined by the user with respect to the mode provided
by the user. Otherwise it will use the
train_prop to divide the dataset into a training and holdout
validation set. This function returns the training and validation
dataset.
Parameters
_mode... | def _apply_holdout(self, _mode='sequential', train_size=0, train_prop=0):
| '\n This function splits the dataset according to the number of\n train_size if defined by the user with respect to the mode provided\n by the user. Other... |
'This function splits the dataset into to the number of n folds
given by the user. Returns an array of folds.
Parameters
nfolds : int, optional
The number of folds for the the validation set.
Returns
WRITEME'
| def split_dataset_nfolds(self, nfolds=0):
| folds_iter = self.iterator(mode='sequential', num_batches=nfolds)
folds = list(folds_iter)
return folds
|
'This function splits the dataset according to the number of
train_size if defined by the user.
Otherwise it will use the train_prop to divide the dataset into a
training and holdout validation set. This function returns the
training and validation dataset.
Parameters
train_size : int
Number of examples that will be as... | def split_dataset_holdout(self, train_size=0, train_prop=0):
| return self._apply_holdout('sequential', train_size, train_prop)
|
'This function splits the dataset using the random_slice and into the
n folds. Returns the folds.
Parameters
nfolds : int
The number of folds for the dataset.
rng : WRITEME
Random number generation class to be used.'
| def bootstrap_nfolds(self, nfolds, rng=None):
| folds_iter = self.iterator(mode='random_slice', num_batches=nfolds, rng=rng)
folds = list(folds_iter)
return folds
|
'This function splits the dataset according to the number of
train_size defined by the user.
Parameters
train_size : int
Number of examples that will be assigned to the training dataset.
nfolds : int
The number of folds for the the validation set.
rng : WRITEME
Random number generation class to be used.'
| def bootstrap_holdout(self, train_size=0, train_prop=0, rng=None):
| return self._apply_holdout('random_slice', train_size, train_prop)
|
'If we view the dataset as providing a stream of random examples to
read, the object returned uniquely identifies our current position in
that stream.'
| def get_stream_position(self):
| return copy.copy(self.rng)
|
'.. todo::
WRITEME properly
Return to a state specified by an object returned from
get_stream_position.
Parameters
pos : object
WRITEME'
| def set_stream_position(self, pos):
| self.rng = copy.copy(pos)
|
'Return to the default initial state of the random example stream.'
| def restart_stream(self):
| self.reset_RNG()
|
'Restore the default seed of the rng used for choosing random
examples.'
| def reset_RNG(self):
| if ('default_rng' not in dir(self)):
self.default_rng = make_np_rng(None, [17, 2, 946], which_method='random_integers')
self.rng = copy.copy(self.default_rng)
|
'.. todo::
WRITEME
Parameters
preprocessor : object
preprocessor object
can_fit : bool, optional
WRITEME'
| def apply_preprocessor(self, preprocessor, can_fit=False):
| preprocessor.apply(self, can_fit)
|
'Convert an array (or the entire dataset) to a topological view.
Parameters
mat : ndarray, 2-dimensional, optional
An array containing a design matrix representation of training
examples. If unspecified, the entire dataset (`self.X`) is used
instead.
This parameter is not named X because X is generally used to
refer to... | def get_topological_view(self, mat=None):
| if (self.view_converter is None):
raise Exception('Tried to call get_topological_view on a dataset that has no view converter')
if (mat is None):
mat = self.X
return self.view_converter.design_mat_to_topo_view(mat)
|
'Convert an array (or the entire dataset) to a destination space.
Parameters
mat : ndarray, 2-dimensional
An array containing a design matrix representation of
training examples.
dspace : Space
A Space we want the data in mat to be formatted in.
It can be a VectorSpace for a design matrix output,
a Conv2DSpace for a to... | def get_formatted_view(self, mat, dspace):
| if (self.view_converter is None):
raise Exception('Tried to call get_formatted_view on a dataset that has no view converter')
self.X_space.np_validate(mat)
return self.view_converter.get_formatted_batch(mat, dspace)
|
'.. todo::
WRITEME properly
Return a view of mat in the topology preserving format. Currently
the same as get_topological_view.
Parameters
mat : ndarray, 2-dimensional
WRITEME'
| def get_weights_view(self, mat):
| if (self.view_converter is None):
raise Exception('Tried to call get_weights_view on a dataset that has no view converter')
return self.view_converter.design_mat_to_weights_view(mat)
|
'Sets the dataset to represent V, where V is a batch
of topological views of examples.
.. todo::
Why is this parameter named \'V\'?
Parameters
V : ndarray
An array containing a design matrix representation of
training examples.
axes : tuple, optional
The axes ordering of the provided topo_view. Must be some
permutation... | def set_topological_view(self, V, axes=('b', 0, 1, 'c')):
| if (len(V.shape) != len(axes)):
raise ValueError(('The topological view must have exactly 4 dimensions, corresponding to %s' % str(axes)))
assert (not contains_nan(V))
rows = V.shape[axes.index(0)]
cols = V.shape[axes.index(1)]
channels = V.shape[axes.index('c')... |
'Return topo (a batch of examples in topology preserving format),
in design matrix format.
Parameters
topo : ndarray, optional
An array containing a topological representation of training
examples. If unspecified, the entire dataset (`self.X`) is used
instead.
Returns
WRITEME'
| def get_design_matrix(self, topo=None):
| if (topo is not None):
if (self.view_converter is None):
raise Exception('Tried to convert from topological_view to design matrix using a dataset that has no view converter')
return self.view_converter.topo_view_to_design_mat(topo)
return ... |
'.. todo::
WRITEME
Parameters
X : ndarray
WRITEME'
| def set_design_matrix(self, X):
| assert (len(X.shape) == 2)
assert (not contains_nan(X))
self.X = X
|
'.. todo::
WRITEME'
| def get_targets(self):
| return self.y
|
'.. todo::
WRITEME
Parameters
batch_size : int
WRITEME
include_labels : bool
WRITEME'
| def get_batch_design(self, batch_size, include_labels=False):
| try:
idx = self.rng.randint(((self.X.shape[0] - batch_size) + 1))
except ValueError:
if (batch_size > self.X.shape[0]):
reraise_as(ValueError(('Requested %d examples from a dataset containing only %d.' % (batch_size, self.X.shape[0]))))
raise
rx = ... |
'.. todo::
WRITEME
Parameters
batch_size : int
WRITEME
include_labels : bool
WRITEME'
| def get_batch_topo(self, batch_size, include_labels=False):
| if include_labels:
(batch_design, labels) = self.get_batch_design(batch_size, True)
else:
batch_design = self.get_batch_design(batch_size)
rval = self.view_converter.design_mat_to_topo_view(batch_design)
if include_labels:
return (rval, labels)
return rval
|
'.. todo::
WRITEME'
| def view_shape(self):
| return self.view_converter.view_shape()
|
'.. todo::
WRITEME'
| def weights_view_shape(self):
| return self.view_converter.weights_view_shape()
|
'.. todo::
WRITEME'
| def has_targets(self):
| return (self.y is not None)
|
'.. todo::
WRITEME properly
Restricts the dataset to include only the examples
in range(start, stop). Ignored if both arguments are None.
Parameters
start : int
start index
stop : int
stop index'
| def restrict(self, start, stop):
| assert ((start is None) == (stop is None))
if (start is None):
return
assert (start >= 0)
assert (stop > start)
assert (stop <= self.X.shape[0])
assert (self.X.shape[0] == self.y.shape[0])
self.X = self.X[start:stop, :]
if (self.y is not None):
self.y = self.y[start:stop,... |
'.. todo::
WRITEME properly
If y exists and is a vector of ints, converts it to a binary matrix
Otherwise will raise some exception
Parameters
min_class : int
WRITEME'
| def convert_to_one_hot(self, min_class=0):
| if (self.y is None):
raise ValueError('Called convert_to_one_hot on a DenseDesignMatrix with no labels.')
if (self.y.ndim != 1):
raise ValueError("Called convert_to_one_hot on a DenseDesignMatrix whose labels aren't scalar.")
if ('int' not in str(... |
'.. todo::
WRITEME
Parameters
X : ndarray
The data to be adjusted'
| def adjust_for_viewer(self, X):
| return (X / np.abs(X).max())
|
'.. todo::
WRITEME
Parameters
X : int
WRITEME
ref : float
WRITEME
per_example : obejct, optional
WRITEME'
| def adjust_to_be_viewed_with(self, X, ref, per_example=None):
| if (per_example is not None):
logger.warning('ignoring per_example')
return np.clip((X / np.abs(ref).max()), (-1.0), 1.0)
|
'Returns the data_specs specifying how the data is internally stored.
This is the format the data returned by `self.get_data()` will be.'
| def get_data_specs(self):
| return self.data_specs
|
'.. todo::
WRITEME properly
Change the axes of the view_converter, if any.
This function is only useful if you intend to call self.iterator
without data_specs, and with "topo=True", which is deprecated.
Parameters
axes : WRITEME
WRITEME'
| def set_view_converter_axes(self, axes):
| assert (self.view_converter is not None)
self.view_converter.set_axes(axes)
self.X_topo_space = self.view_converter.topo_space
|
'Sanity checks for X_labels and y_labels.'
| def _check_labels(self):
| if (self.X_labels is not None):
assert (self.X is not None)
assert (self.view_converter is None)
assert (self.X.ndim <= 2)
if (self.y_labels is not None):
assert (self.y is not None)
assert (self.y.ndim <= 2)
|
'.. todo::
WRITEME'
| def set_design_matrix(self, X, start=0):
| assert (len(X.shape) == 2)
assert (not contains_nan(X))
DenseDesignMatrixPyTables.fill_hdf5(file_handle=self.h5file, data_x=X, start=start)
|
'Sets the dataset to represent V, where V is a batch
of topological views of examples.
.. todo::
Why is this parameter named \'V\'?
Parameters
V : ndarray
An array containing a design matrix representation of training examples.
axes : tuple, optional
The axes ordering of the provided topo_view. Must be some... | def set_topological_view(self, V, axes=('b', 0, 1, 'c'), start=0):
| assert (not contains_nan(V))
rows = V.shape[axes.index(0)]
cols = V.shape[axes.index(1)]
channels = V.shape[axes.index('c')]
self.view_converter = DefaultViewConverter([rows, cols, channels], axes=axes)
X = self.view_converter.topo_view_to_design_mat(V)
assert (not contains_nan(X))
Dense... |
'Initializes the hdf5 file into which the data will be stored. This must
be called before calling fill_hdf5.
Parameters
path : string
The name of the hdf5 file.
shapes : tuple
The shapes of X and y.
title : string, optional
Name of the dataset. e.g. For SVHN, set this to "SVHN Dataset".
"Pytables Dataset" is used as ti... | def init_hdf5(self, path, shapes, title='Pytables Dataset', y_dtype='float'):
| assert (y_dtype in ['float', 'int']), "y_dtype can be 'float' or 'int' only"
(x_shape, y_shape) = shapes
ensure_tables()
h5file = tables.openFile(path, mode='w', title=title)
gcolumns = h5file.createGroup(h5file.root, 'Data', 'Data')
atom = (tables.Float32Atom() if (config.floa... |
'Saves the data to the hdf5 file.
PyTables tends to crash if you write large amounts of data into them
at once. As such this function writes data in batches.
Parameters
file_handle : hdf5 file handle
Handle to an hdf5 object.
data_x : nd array
X data. Must be the same shape as specified to init_hdf5.
data_y : nd array,... | @staticmethod
def fill_hdf5(file_handle, data_x, data_y=None, node=None, start=0, batch_size=5000):
| if (node is None):
node = file_handle.getNode('/', 'Data')
data_size = data_x.shape[0]
last = (np.floor((data_size / float(batch_size))) * batch_size)
for i in xrange(0, data_size, batch_size):
stop = ((i + np.mod(data_size, batch_size)) if (i >= last) else (i + batch_size))
asse... |
'Resizes the X and y tables. This must be called before calling
fill_hdf5.
Parameters
h5file : hdf5 file handle
Handle to an hdf5 object.
start : int
The start index to write data.
stop : int
The index of the record following the last record to be written.'
| def resize(self, h5file, start, stop):
| ensure_tables()
data = h5file.getNode('/', 'Data')
try:
gcolumns = h5file.createGroup('/', 'Data_', 'Data')
except tables.exceptions.NodeError:
h5file.removeNode('/', 'Data_', 1)
gcolumns = h5file.createGroup('/', 'Data_', 'Data')
start = (0 if (start is None) else start)
... |
'.. todo::
WRITEME'
| def view_shape(self):
| return self.shape
|
'.. todo::
WRITEME'
| def weights_view_shape(self):
| return self.shape
|
'Returns a topological view/copy of design matrix.
Parameters
design_matrix: numpy.ndarray
A design matrix with data in rows. Data is assumed to be laid out in
memory according to the axis order (\'b\', \'c\', 0, 1)
returns: numpy.ndarray
A matrix with axis order given by self.axes and batch shape given by
self.shape (... | def design_mat_to_topo_view(self, design_matrix):
| if (len(design_matrix.shape) != 2):
raise ValueError(('design_matrix must have 2 dimensions, but shape was %s.' % str(design_matrix.shape)))
expected_row_size = np.prod(self.shape)
if (design_matrix.shape[1] != expected_row_size):
raise ValueError(("This DefaultVie... |
'.. todo::
WRITEME'
| def design_mat_to_weights_view(self, X):
| rval = self.design_mat_to_topo_view(X)
rval = np.transpose(rval, tuple((self.axes.index(axis) for axis in ('b', 0, 1, 'c'))))
return rval
|
'Returns a design matrix view/copy of topological matrix.
Parameters
topo_array: numpy.ndarray
An N-D array with axis order given by self.axes. Non-batch axes\'
dimension sizes must agree with corresponding sizes in self.shape.
returns: numpy.ndarray
A design matrix with data in rows. Data, is laid out in memory
accord... | def topo_view_to_design_mat(self, topo_array):
| for (shape_elem, axis) in safe_zip(self.shape, (0, 1, 'c')):
if (topo_array.shape[self.axes.index(axis)] != shape_elem):
raise ValueError("topo_array's %s axis has a different size (%d) from the corresponding size (%d) in self.shape.\n self.shape:... |
'.. todo::
WRITEME properly
Reformat batch from the internal storage format into dspace.'
| def get_formatted_batch(self, batch, dspace):
| if isinstance(dspace, VectorSpace):
return dspace.np_format_as(batch, dspace)
elif isinstance(dspace, Conv2DSpace):
topo_batch = self.design_mat_to_topo_view(batch)
if (self.topo_space.axes != self.axes):
warnings.warn(('It looks like %s.axes has been change... |
'.. todo::
WRITEME'
| def __setstate__(self, d):
| if ('axes' not in d):
d['axes'] = ['b', 0, 1, 'c']
self.__dict__.update(d)
if ('topo_space' not in self.__dict__):
self._update_topo_space()
|
'Update self.topo_space from self.shape and self.axes'
| def _update_topo_space(self):
| (rows, cols, channels) = self.shape
self.topo_space = Conv2DSpace(shape=(rows, cols), num_channels=channels, axes=self.axes)
|
'.. todo::
WRITEME'
| def set_axes(self, axes):
| self.axes = axes
self._update_topo_space()
|
'.. todo::
WRITEME'
| def __init__(self, num_examples, rng=(2013, 5, 17)):
| rng = make_np_rng(rng, self._default_seed, which_method='uniform')
X = rng.uniform((-1), 1, size=(num_examples, 2))
y = _four_regions_labels(X)
super(FourRegions, self).__init__(X=X, y=y, y_labels=4)
|
'.. todo::
WRITEME'
| def __init__(self, min_x=(-6.28), max_x=6.28, std=0.05, rng=None):
| (self.min_x, self.max_x, self.std) = (min_x, max_x, std)
rng = make_np_rng(rng, [17, 2, 946], which_method=['uniform', 'randn'])
self.default_rng = copy.copy(rng)
self.rng = rng
|
'.. todo::
WRITEME'
| def energy(self, mat):
| x = mat[:, 0]
y = mat[:, 1]
rval = (((y - N.cos(x)) ** 2.0) / (2.0 * (self.std ** 2.0)))
return rval
|
'.. todo::
WRITEME properly
This dataset can generate an infinite amount of examples.
This function gives the pdf from which the examples are drawn.'
| def pdf_func(self, mat):
| x = mat[:, 0]
y = mat[:, 1]
rval = N.exp(((- ((y - N.cos(x)) ** 2.0)) / (2.0 * (self.std ** 2.0))))
rval /= N.sqrt(((2.0 * N.pi) * (self.std ** 2.0)))
rval /= (self.max_x - self.min_x)
rval *= (x < self.max_x)
rval *= (x > self.min_x)
return rval
|
'.. todo::
WRITEME properly
This dataset can generate an infinite amount of examples.
This function gives the energy function for the distribution from
which the examples are drawn.'
| def free_energy(self, X):
| x = X[:, 0]
y = X[:, 1]
rval = (T.sqr((y - T.cos(x))) / (2.0 * (self.std ** 2.0)))
mask = (x < self.max_x)
mask = (mask * (x > self.min_x))
rval = ((mask * rval) + ((1 - mask) * 1e+30))
return rval
|
'.. todo::
WRITEME properly
This dataset can generate an infinite amount of examples.
This function gives the pdf from which the examples are drawn.'
| def pdf(self, X):
| x = X[:, 0]
y = X[:, 1]
rval = T.exp(((- T.sqr((y - T.cos(x)))) / (2.0 * (self.std ** 2.0))))
rval /= N.sqrt(((2.0 * N.pi) * (self.std ** 2.0)))
rval /= (self.max_x - self.min_x)
rval *= (x < self.max_x)
rval *= (x > self.min_x)
return rval
|
'.. todo::
WRITEME'
| def get_stream_position(self):
| return copy.copy(self.rng)
|
'.. todo::
WRITEME'
| def set_stream_position(self, s):
| self.rng = copy.copy(s)
|
'.. todo::
WRITEME'
| def restart_stream(self):
| self.reset_RNG()
|
'.. todo::
WRITEME'
| def reset_RNG(self):
| if ('default_rng' not in dir(self)):
self.default_rng = N.random.RandomState([17, 2, 946])
self.rng = copy.copy(self.default_rng)
|
'.. todo::
WRITEME'
| def apply_preprocessor(self, preprocessor, can_fit=False):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| def get_batch_design(self, batch_size):
| x = N.cast[config.floatX](self.rng.uniform(self.min_x, self.max_x, (batch_size, 1)))
y = (N.cos(x) + (N.cast[config.floatX](self.rng.randn(*x.shape)) * self.std))
rval = N.hstack((x, y))
return rval
|
'.. todo::
WRITEME'
| def adjust_for_viewer(self, X):
| return N.clip(((X * 2.0) - 1.0), (-1.0), 1.0)
|
'.. todo::
WRITEME'
| def adjust_to_be_viewed_with(self, X, other, per_example=False):
| return self.adjust_for_viewer(X)
|
'.. todo::
WRITEME'
| def get_test_set(self):
| args = {}
args.update(self.args)
del args['self']
args['which_set'] = 'test'
args['start'] = None
args['stop'] = None
args['fit_preprocessor'] = args['fit_test_preprocessor']
args['fit_test_preprocessor'] = None
return MNIST(**args)
|
'.. todo::
WRITEME'
| def get_test_set(self):
| return SVHN(which_set='test', path=self.path, center=self.center, scale=self.scale, start=self.start, stop=self.stop, axes=self.axes, preprocessor=self.preprocessor)
|
'.. todo::
WRITEME'
| def make_data(self, which_set, path, shuffle=True):
| sizes = {'train': 73257, 'test': 26032, 'extra': 531131, 'train_all': 604388, 'valid': 6000, 'splitted_train': 598388}
image_size = ((32 * 32) * 3)
h_file_n = '{0}_32x32.h5'.format(os.path.join(path, 'h5', which_set))
(h5file, node) = self.init_hdf5(h_file_n, ([sizes[which_set], image_size], [sizes[whic... |
'.. todo::
WRITEME'
| def get_test_set(self):
| return SVHN_On_Memory(which_set='test', path=self.path, center=self.center, scale=self.scale, start=self.start, stop=self.stop, axes=self.axes, preprocessor=self.preprocessor)
|
'.. todo::
WRITEME'
| def make_data(self, which_set, path, shuffle=True):
| sizes = {'train': 73257, 'test': 26032, 'extra': 531131, 'train_all': 604388, 'valid': 6000, 'splitted_train': 598388}
image_size = ((32 * 32) * 3)
rng = make_np_rng(None, 322, which_method='shuffle')
def design_matrix_view(data_x):
'reshape data_x to deisng matrix view\n ... |
'Return an iterator for this dataset'
| def __iter__(self):
| return self.iterator()
|
'Return an iterator for this dataset with the specified
behaviour. Unspecified values are filled-in by the default.
Parameters
mode : str or object, optional
One of \'sequential\', \'random_slice\', or \'random_uniform\',
*or* a class that instantiates an iterator that returns
slices or index sequences on every call to... | def iterator(self, mode=None, batch_size=None, num_batches=None, rng=None, data_specs=None, return_tuple=False):
| raise NotImplementedError()
|
'Fill-in unspecified attributes trying to set them to their default
values or raising an error.
Parameters
mode : str or object, optional
batch_size : int, optional
num_batches : int, optional
rng : int, object or array_like, optional
data_specs : (space, source) pair, optional
Refer to `dataset.iterator` for a detaile... | def _init_iterator(self, mode=None, batch_size=None, num_batches=None, rng=None, data_specs=None):
| if (data_specs is None):
if hasattr(self, '_iter_data_specs'):
data_specs = self._iter_data_specs
else:
raise ValueError(('data_specs not provided and no default data spec set for %s' % str(self)))
if (mode is None):
if hasattr(self, ... |
'Shift and scale a tensor, mapping its data range to [-1, 1].
It makes it possible for the transformed tensor to be displayed
with `pylearn2.gui.patch_viewer` tools.
Default is to do nothing.
Parameters
X: `numpy.ndarray`
a tensor in the same space as the data
Returns
`numpy.ndarray`
X shifted and scaled by a transform... | def adjust_for_viewer(self, X):
| return X
|
'Returns true if the dataset includes targets'
| def has_targets(self):
| raise NotImplementedError()
|
'Returns the index of the axis that corresponds to different examples
in a batch when using topological_view.
WARNING: This method is deprecated and will be unsupported after 27
July 27, 2015. Some classes, e.g. DenseDesignMatrix, might still
implement it, but it will not be part of the interface anymore.'
| def get_topo_batch_axis(self):
| warnings.warn('This method is deprecated and will be unsupported after 27 July 27, 2015')
raise NotImplementedError()
|
'Returns a randomly chosen batch of data formatted as a design
matrix.
This method is not guaranteed to have any particular properties
like not repeating examples, etc. It is mostly useful for getting
a single batch of data for a unit test or a quick-and-dirty
visualization. Using this method for serious learning code ... | def get_batch_design(self, batch_size, include_labels=False):
| warnings.warn('This method is deprecated and will be unsupported after 27 July 27, 2015')
raise NotImplementedError((str(type(self)) + ' does not implement get_batch_design.'))
|
'Returns a topology-preserving batch of data.
This method is not guaranteed to have any particular properties
like not repeating examples, etc. It is mostly useful for getting
a single batch of data for a unit test or a quick-and-dirty
visualization. Using this method for serious learning code is
strongly discouraged. ... | def get_batch_topo(self, batch_size, include_labels=False):
| warnings.warn('This method is deprecated and will be unsupported after 27 July 27, 2015')
raise NotImplementedError()
|
'Returns the number of examples in the dataset
Notes
Infinite datasets have float(\'inf\') examples.'
| def get_num_examples(self):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| def adjust_for_viewer(self, X):
| rval = X.copy()
if (not hasattr(self, 'center')):
self.center = False
if (not hasattr(self, 'rescale')):
self.rescale = False
if (not hasattr(self, 'gcn')):
self.gcn = False
if (self.gcn is not None):
rval = X.copy()
for i in xrange(rval.shape[0]):
... |
'.. todo::
WRITEME'
| def adjust_to_be_viewed_with(self, X, orig, per_example=False):
| rval = X.copy()
if (not hasattr(self, 'center')):
self.center = False
if (not hasattr(self, 'rescale')):
self.rescale = False
if (not hasattr(self, 'gcn')):
self.gcn = False
if (self.gcn is not None):
rval = X.copy()
if per_example:
for i in xrange... |
'.. todo::
WRITEME'
| def get_test_set(self):
| return CIFAR10(which_set='test', center=self.center, rescale=self.rescale, gcn=self.gcn, toronto_prepro=self.toronto_prepro, axes=self.axes)
|
'.. todo::
WRITEME'
| def __init__(self, which_set, center=False, example_range=None):
| if (which_set == 'train'):
train = load('${PYLEARN2_DATA_PATH}/stl10/stl10_matlab/train.mat')
self.class_names = [array[0].encode('utf-8') for array in train['class_names'][0]]
fold_indices = train['fold_indices']
assert (fold_indices.shape == (1, 10))
self.fold_indices = np.... |
'.. todo::
WRITEME'
| def __init__(self, which_set, axes=['b', 0, 1, 'c']):
| self.args = locals()
assert (which_set in self.data_split.keys())
path = serial.preprocess('${PYLEARN2_DATA_PATH}/ocr_letters/letter.data')
with open(path, 'r') as data_f:
data = data_f.readlines()
data = [line.split(' DCTB ') for line in data]
data_x = [map(int, item[6:(-1)]) for it... |
'.. todo::
WRITEME'
| def get_test_set(self):
| return OCR('test')
|
'Returns the test set.'
| def get_test_set(self):
| yaml = self.preprocessed_dataset.yaml_src
yaml = yaml.replace('train', 'test')
args = {}
args.update(self.args)
del args['self']
args['start'] = None
args['stop'] = None
args['preprocessed_dataset'] = yaml_parse.load(yaml)
return ZCA_Dataset(**args)
|
'Formats examples for use with PatchViewer
Parameters
X : 2d numpy array
One example per row
Returns
output : 2d numpy array
One example per row, rescaled so the maximum absolute value
within each row is (almost) 1.'
| def adjust_for_viewer(self, X):
| rval = X.copy()
for i in xrange(rval.shape[0]):
rval[i, :] /= (np.abs(rval[i, :]).max() + 1e-12)
return rval
|
'Adjusts `X` using the same transformation that would
be applied to `other` if `other` were passed to
`adjust_for_viewer`. This is useful for visualizing `X`
alongside `other`.
Parameters
X : 2d ndarray
Examples to be adjusted
other : 2d ndarray
Examples that define the scale
per_example : bool
Default: False. If True,... | def adjust_to_be_viewed_with(self, X, other, per_example=False):
| assert (X.shape == other.shape), (X.shape, other.shape)
rval = X.copy()
if per_example:
for i in xrange(rval.shape[0]):
rval[i, :] /= np.abs(other[i, :]).max()
else:
rval /= np.abs(other).max()
rval = np.clip(rval, (-1.0), 1.0)
return rval
|
'Map `X` back to the original space (before ZCA preprocessing)
and adjust it for display with PatchViewer.
Parameters
X : 2d numpy array
The examples to be mapped back and adjusted
Returns
output : 2d numpy array
The examples in the original space, adjusted for display'
| def mapback_for_viewer(self, X):
| assert (X.ndim == 2)
rval = self.preprocessor.inverse(X)
rval = self.preprocessed_dataset.adjust_for_viewer(rval)
return rval
|
'Map `X` back to the original space (before ZCA preprocessing)
Parameters
X : 2d numpy array
The examples to be mapped back
Returns
output : 2d numpy array
The examples in the original space'
| def mapback(self, X):
| return self.preprocessor.inverse(X)
|
'Creates an NpyDataset object.
Parameters
file : file-like object or str
A file-like object or string indicating a filename. Passed
directly to `numpy.load`.
mmap_mode : str, optional
Memory mapping options for memory-mapping an array on disk,
rather than loading it into memory. See the `numpy.load`
docstring for detai... | def __init__(self, file, mmap_mode=None):
| self._path = file
self._loaded = False
|
'.. todo::
WRITEME'
| def _deferred_load(self):
| self._loaded = True
loaded = numpy.load(self._path)
assert isinstance(loaded, numpy.ndarray), 'single arrays (.npy) only'
if (len(loaded.shape) == 2):
super(NpyDataset, self).__init__(X=loaded)
else:
super(NpyDataset, self).__init__(topo_view=loaded)
|
'Creates an NpzDataset object.
Parameters
file : file-like object or str
A file-like object or string indicating a filename. Passed
directly to `numpy.load`.
key : str
A string indicating which key name to use to pull out the
input data.
target_key : str, optional
A string indicating which key name to use to pull out t... | def __init__(self, file, key, target_key=None):
| loaded = numpy.load(file)
assert (not isinstance(loaded, numpy.ndarray)), 'zipped groups of arrays (.npz) only'
assert (key in loaded), ('%s not found in loaded NPZFile' % key)
if (target_key is not None):
assert (target_key in loaded), ('%s not found in ... |
'Loads the data from a CSV file (ending with a \'.csv\' filename).
Returns
X : object
The features of the dataset.
y : object, optional
The target variable of the model.'
| def _load_data(self):
| assert self.path.endswith('.csv')
if self.expect_headers:
data = np.loadtxt(self.path, delimiter=self.delimiter, skiprows=1)
else:
data = np.loadtxt(self.path, delimiter=self.delimiter)
def take_subset(X, y):
'\n Take... |
'.. todo::
WRITEME'
| def __init__(self):
| view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3))
super(DebugDataset, self).__init__(X=N.asarray([[1.0, 0.0], [0.0, 1.0]]), view_converter=view_converter)
assert (not N.any(N.isnan(self.X)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.