desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Adjusts the data to be compatible with a viewer that expects values to
be in [-1, 1].
Parameters
X : numpy.ndarray
Data'
| def adjust_for_viewer(self, X):
| return numpy.clip(((X * 2.0) - 1.0), (-1.0), 1.0)
|
'Adjusts the data to be compatible with a viewer that expects values to
be in [-1, 1].
Parameters
X : numpy.ndarray
Data
other : WRITEME
per_example : WRITEME'
| def adjust_to_be_viewed_with(self, X, other, per_example=False):
| return self.adjust_for_viewer(X)
|
'Returns the test set corresponding to this BinarizedMNIST instance'
| 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 BinarizedMNIST(**args)
|
'.. todo::
WRITEME'
| def __init__(self, preprocessor=None, start=None, stop=None):
| self.class_names = ['DIE', 'LIVE']
lines = hepatitis_data.split('\n')
X = []
y = []
for line in lines:
row = line.split(',')
row = [neg_missing(elem) for elem in row]
X.append([float(elem) for elem in row[1:]])
y.append(float(row[0]))
X = np.array(X)
NUM_FEATURES = 19
NUM_EXAMPLES = 155
NUM_CLASSES = 2
(AGE, SEX, STEROID, ANTIVIRALS, FATIGUE, MALAISE, ANOREXIA, LIVER_BIG, LIVER_FIRM, SPLEEN_PALPABLE, SPIDERS, ASCITES, VARICES, BILIRUBIN, ALK_PHOSPHATE, SGOT, ALBUMIN, PROTIME, HISTOLOGY) = range(NUM_FEATURES)
real_mask = np.zeros((NUM_FEATURES,), dtype='bool')
real_mask[[AGE, BILIRUBIN, ALK_PHOSPHATE, SGOT, ALBUMIN, PROTIME, HISTOLOGY]] = 1
real_X = X[:, real_mask]
binary_mask = (1 - real_mask).astype('bool')
binary_X = X[:, binary_mask]
binary_X[(binary_X == 1)] = 0
binary_X[(binary_X == 2)] = 1
for i in xrange(binary_X.shape[0]):
for j in xrange(binary_X.shape[1]):
assert (binary_X[(i, j)] in [(-1.0), 0.0, 1.0]), (binary_X[(i, j)], i, j)
X = np.concatenate((real_X, binary_X), axis=1)
assert (X.shape == (NUM_EXAMPLES, NUM_FEATURES))
assert (len(y) == NUM_EXAMPLES)
y = (np.asarray(y) - 1)
assert (min(y) == 0)
assert (max(y) == (NUM_CLASSES - 1))
super(Hepatitis, self).__init__(X=X, y=y, y_labels=NUM_CLASSES, preprocessor=preprocessor)
self.restrict(start, stop)
|
'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'
| def get_data(self):
| return self.data
|
'.. todo::
WRITEME'
| def set_data(self, data, data_specs):
| data_specs[0].np_validate(data)
assert (not [contains_nan(X) for X in data])
raise NotImplementedError()
|
'.. todo::
WRITEME'
| def get_source(self, name):
| raise NotImplementedError()
|
'.. todo::
WRITEME'
| def get_batch(self, batch_size, data_specs=None):
| raise NotImplementedError()
'\n try:\n idx = self.rng.randint(self.X.shape[0] - batch_size + 1)\n except ValueError:\n if batch_size > self.X.shape[0]:\n raise ValueError("Requested "+str(batch_size)+" examples"\n "from a dataset containing only "+str(self.X.shape[0]))\n raise\n rx = self.X[idx:idx + batch_size, :]\n if include_labels:\n if self.y is None:\n return rx, None\n ry = self.y[idx:idx + batch_size]\n return rx, ry\n rx = np.cast[config.floatX](rx)\n return rx\n '
|
'Return the test set'
| def get_test_set(self, fold=None):
| args = {}
args.update(self.args)
del args['self']
args['which_set'] = 'test'
if (fold is not None):
args['fold'] = fold
return TFD(**args)
|
'.. todo::
WRITEME'
| def __init__(self, img_shp, rings):
| self.img_shp = img_shp
self.rings = rings
|
'.. todo::
WRITEME'
| def apply(self, dataset, can_fit=False):
| X = dataset.get_design_matrix()
topo_X = self.perform(X)
dataset.set_topological_view(topo_X)
|
'.. todo::
WRITEME'
| def perform(self, X):
| return decode(X, self.img_shp, self.rings)
|
'.. todo::
WRITEME'
| def design_mat_to_topo_view(self, X):
| return self.decoder.perform(X)
|
'.. todo::
WRITEME'
| def design_mat_to_weights_view(self, X):
| return self.design_mat_to_topo_view(X)
|
'.. todo::
WRITEME'
| def topo_view_to_design_mat(self, V):
| return self.encoder.perform(V)
|
'.. todo::
WRITEME'
| def __init__(self, f, rank=0, debug=False):
| self.f = f
(self.magic_t, self.elsize, self.ndim, self.dim, self.dim_size) = read_header(f, debug)
self.f_start = f.tell()
if (rank <= self.ndim):
self.readshape = tuple(self.dim[(self.ndim - rank):])
else:
self.readshape = tuple(self.dim)
if (rank <= self.ndim):
padding = tuple()
else:
padding = ((1,) * (rank - self.ndim))
self.returnshape = (padding + self.readshape)
self.readsize = _prod(self.readshape)
if debug:
logger.debug('READ PARAM {0} {1}'.format(self.readshape, self.returnshape, self.readsize))
|
'.. todo::
WRITEME'
| def __len__(self):
| return _prod(self.dim[:(self.ndim - len(self.readshape))])
|
'.. todo::
WRITEME'
| def __getitem__(self, idx):
| if (idx >= len(self)):
raise IndexError(idx)
self.f.seek((self.f_start + ((idx * self.elsize) * self.readsize)))
return numpy.fromfile(self.f, dtype=self.magic_t, count=self.readsize).reshape(self.returnshape)
|
'.. todo::
WRITEME properly
Parameters
raw : pylearn2 Dataset
Provides raw data
transformer: pylearn2 Block
To transform the data'
| def __init__(self, raw, transformer, cpu_only=False, space_preserving=False):
| self.__dict__.update(locals())
del self.self
|
'.. todo::
WRITEME'
| def get_batch_design(self, batch_size, include_labels=False):
| raw = self.raw.get_batch_design(batch_size, include_labels)
if include_labels:
(X, y) = raw
else:
X = raw
X = self.transformer.perform(X)
if include_labels:
return (X, y)
return X
|
'.. todo::
WRITEME'
| def get_test_set(self):
| return TransformerDataset(raw=self.raw.get_test_set(), transformer=self.transformer, cpu_only=self.cpu_only, space_preserving=self.space_preserving)
|
'If the transformer has changed the space, we don\'t have a good
idea of how to do topology in the new space.
If the transformer just changes the values in the original space,
we can have the raw dataset provide the topology.'
| def get_batch_topo(self, batch_size):
| X = self.get_batch_design(batch_size)
if self.space_preserving:
return self.raw.get_topological_view(X)
return X.reshape(X.shape[0], X.shape[1], 1, 1)
|
'.. todo::
WRITEME'
| def iterator(self, mode=None, batch_size=None, num_batches=None, rng=None, data_specs=None, return_tuple=False):
| if (data_specs is not None):
assert is_flat_specs(data_specs)
(space, source) = data_specs
if (not isinstance(source, tuple)):
source = (source,)
if isinstance(space, CompositeSpace):
space = tuple(space.components)
else:
space = (space,)
if ('features' not in source):
raw_data_specs = data_specs
else:
feature_idx = source.index('features')
if self.space_preserving:
feature_input_space = space[feature_idx]
else:
feature_input_space = self.transformer.get_input_space()
raw_space = CompositeSpace((((feature_input_space,) + space[:feature_idx]) + space[(feature_idx + 1):]))
raw_source = ((('features',) + source[:feature_idx]) + source[(feature_idx + 1):])
raw_data_specs = (raw_space, raw_source)
else:
raw_data_specs = None
raw_iterator = self.raw.iterator(mode=mode, batch_size=batch_size, num_batches=num_batches, rng=rng, data_specs=raw_data_specs, return_tuple=return_tuple)
final_iterator = TransformerIterator(raw_iterator, self, data_specs=data_specs)
return final_iterator
|
'.. todo::
WRITEME'
| def has_targets(self):
| return self.raw.has_targets()
|
'.. todo::
WRITEME'
| def adjust_for_viewer(self, X):
| if self.space_preserving:
return self.raw.adjust_for_viewer(X)
return X
|
'.. todo::
WRITEME'
| def get_weights_view(self, *args, **kwargs):
| if self.space_preserving:
return self.raw.get_weights_view(*args, **kwargs)
raise NotImplementedError()
|
'.. todo::
WRITEME'
| def get_topological_view(self, *args, **kwargs):
| if self.space_preserving:
return self.raw.get_weights_view(*args, **kwargs)
raise NotImplementedError()
|
'.. todo::
WRITEME'
| def adjust_to_be_viewed_with(self, *args, **kwargs):
| return self.raw.adjust_to_be_viewed_with(*args, **kwargs)
|
'.. todo::
WRITEME'
| def __init__(self, raw_iterator, transformer_dataset, data_specs):
| self.raw_iterator = raw_iterator
self.transformer_dataset = transformer_dataset
self.stochastic = raw_iterator.stochastic
self.uneven = raw_iterator.uneven
self.data_specs = data_specs
|
'.. todo::
WRITEME'
| def __iter__(self):
| return self
|
'.. todo::
WRITEME'
| def __next__(self):
| raw_batch = self.raw_iterator.next()
transformer = self.transformer_dataset.transformer
out_space = self.data_specs[0]
if isinstance(out_space, CompositeSpace):
out_space = out_space.components[0]
if self.transformer_dataset.space_preserving:
rval_space = out_space
else:
rval_space = transformer.get_output_space()
def transform(X_batch):
rval = transformer.perform(X_batch)
if (rval_space != out_space):
rval = rval_space.np_format_as(rval, out_space)
return rval
if (not isinstance(raw_batch, tuple)):
rval = transform(raw_batch)
else:
rval = ((transform(raw_batch[0]),) + raw_batch[1:])
return rval
|
'.. todo::
WRITEME'
| @property
def num_examples(self):
| return self.raw_iterator.num_examples
|
'.. todo::
WRITEME'
| @classmethod
def load(cls, which_set, desc):
| assert (desc in ['dat', 'cat', 'info'])
base = '%s/norb_small/original_npy/smallnorb-'
base = (base % os.getenv('PYLEARN2_DATA_PATH'))
if (which_set == 'train'):
base += '5x46789x9x18x6x2x96x96-training'
else:
base += '5x01235x9x18x6x2x96x96-testing'
fname = (base + ('-%s.npy' % desc))
fname = datasetCache.cache_file(fname)
fp = open(fname, 'r')
data = np.load(fp)
fp.close()
return data
|
'.. todo::
WRITEME'
| def get_test_set(self):
| test_args = {'which_set': 'test'}
for key in self.args:
if (key in ['which_set', 'restrict_instances', 'self', 'start', 'stop']):
continue
test_args[key] = self.args[key]
return FoveatedNORB(**test_args)
|
'.. todo::
WRITEME'
| def restrict_instances(self, instances):
| mask = reduce(np.maximum, [(self.instance == ins) for ins in instances])
mask = mask.astype('bool')
self.instance = self.instance[mask]
self.X = self.X[mask, :]
if (self.y.ndim == 2):
self.y = self.y[mask, :]
else:
self.y = self.y[mask]
assert (self.X.shape[0] == self.y.shape[0])
expected = sum([(self.instance == ins).sum() for ins in instances])
assert (self.X.shape[0] == expected)
|
'.. todo::
WRITEME'
| def adjust_for_viewer(self, X):
| rval = X.copy()
if (not hasattr(self, 'center')):
self.center = 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]):
rval[i, :] /= np.abs(rval[i, :]).max()
return rval
if (not self.center):
rval -= 127.5
rval /= 127.5
rval = np.clip(rval, (-1.0), 1.0)
return rval
|
'.. 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, 'gcn')):
self.gcn = False
if (self.gcn is not None):
rval = X.copy()
if per_example:
for i in xrange(rval.shape[0]):
rval[i, :] /= np.abs(orig[i, :]).max()
else:
rval /= np.abs(orig).max()
rval = np.clip(rval, (-1.0), 1.0)
return rval
if (not self.center):
rval -= 127.5
rval /= 127.5
rval = np.clip(rval, (-1.0), 1.0)
return rval
|
'.. todo::
WRITEME'
| def get_test_set(self):
| return CIFAR100(which_set='test', center=self.center, gcn=self.gcn, toronto_prepro=self.toronto_prepro, axes=self.axes)
|
'Returns the category string corresponding to an integer category label.'
| @classmethod
def get_category(cls, scalar_label):
| return cls._categories[int(scalar_label)]
|
'Returns the elevation, in degrees, corresponding to an integer
elevation label.'
| @classmethod
def get_elevation_degrees(cls, scalar_label):
| scalar_label = int(scalar_label)
assert (scalar_label >= 0)
assert (scalar_label < 9)
return (30 + (5 * scalar_label))
|
'Returns the azimuth, in degrees, corresponding to an integer
label.'
| @classmethod
def get_azimuth_degrees(cls, scalar_label):
| scalar_label = int(scalar_label)
assert (scalar_label >= 0)
assert (scalar_label <= 34)
assert ((scalar_label % 2) == 0)
return (scalar_label * 10)
|
'parameters
which_set : str
Must be \'train\' or \'test\'.
multi_target : bool
If False, each label is an integer labeling the image catergory. If
True, each label is a vector: [category, instance, lighting,
elevation, azimuth]. All labels are given as integers. Use the
categories, elevation_degrees, and azimuth_degrees arrays to map
from these integers to actual values.'
| def __init__(self, which_set, multi_target=False, stop=None):
| assert (which_set in ['train', 'test'])
self.which_set = which_set
subtensor = (slice(0, stop) if (stop is not None) else None)
X = SmallNORB.load(which_set, 'dat', subtensor=subtensor)
X = theano._asarray(X, theano.config.floatX)
X = X.reshape((-1), (2 * numpy.prod(self.original_image_shape)))
y = SmallNORB.load(which_set, 'cat', subtensor=subtensor)
if multi_target:
y_extra = SmallNORB.load(which_set, 'info', subtensor=subtensor)
y = numpy.hstack((y[:, numpy.newaxis], y_extra))
datum_shape = (((2,) + self.original_image_shape) + (1,))
axes = ('b', 's', 0, 1, 'c')
view_converter = StereoViewConverter(datum_shape, axes)
super(SmallNORB, self).__init__(X=X, y=y, y_labels=(numpy.max(y) + 1), view_converter=view_converter)
|
'Reads and returns a single file as a numpy array.'
| @classmethod
def load(cls, which_set, filetype, subtensor):
| assert (which_set in ['train', 'test'])
assert (filetype in ['dat', 'cat', 'info'])
def getPath(which_set):
dirname = os.path.join(os.getenv('PYLEARN2_DATA_PATH'), 'norb_small/original')
if (which_set == 'train'):
instance_list = '46789'
elif (which_set == 'test'):
instance_list = '01235'
filename = ('smallnorb-5x%sx9x18x6x2x96x96-%s-%s.mat' % (instance_list, (which_set + 'ing'), filetype))
return os.path.join(dirname, filename)
def parseNORBFile(file_handle, subtensor=None, debug=False):
"\n Load all or part of file 'file_handle' into a numpy ndarray\n\n .. todo::\n\n WRITEME properly\n\n :param file_handle: file from which to read file can be opended\n with open(), gzip.open() and bz2.BZ2File()\n @type file_handle: file-like object. Can be a gzip open file.\n\n :param subtensor: If subtensor is not None, it should be like the\n argument to numpy.ndarray.__getitem__. The following two\n expressions should return equivalent ndarray objects, but the one\n on the left may be faster and more memory efficient if the\n underlying file f is big.\n\n read(file_handle, subtensor) <===> read(file_handle)[*subtensor]\n\n Support for subtensors is currently spotty, so check the code to\n see if your particular type of subtensor is supported.\n "
def readNums(file_handle, num_type, count):
'\n Reads 4 bytes from file, returns it as a 32-bit integer.\n '
num_bytes = (count * numpy.dtype(num_type).itemsize)
string = file_handle.read(num_bytes)
return numpy.fromstring(string, dtype=num_type)
def readHeader(file_handle, debug=False, from_gzip=None):
'\n .. todo::\n\n WRITEME properly\n\n :param file_handle: an open file handle.\n :type file_handle: a file or gzip.GzipFile object\n\n :param from_gzip: bool or None\n :type from_gzip: if None determine the type of file handle.\n\n :returns: data type, element size, rank, shape, size\n '
if (from_gzip is None):
from_gzip = isinstance(file_handle, (gzip.GzipFile, bz2.BZ2File))
key_to_type = {507333713: ('float32', 4), 507333715: ('float64', 8), 507333716: ('int32', 4), 507333717: ('uint8', 1), 507333718: ('int16', 2)}
type_key = readNums(file_handle, 'int32', 1)[0]
(elem_type, elem_size) = key_to_type[type_key]
if debug:
logger.debug("header's type key, type, type size: {0} {1} {2}".format(type_key, elem_type, elem_size))
if (elem_type == 'packed matrix'):
raise NotImplementedError('packed matrix not supported')
num_dims = readNums(file_handle, 'int32', 1)[0]
if debug:
logger.debug('# of dimensions, according to header: {0}'.format(num_dims))
if from_gzip:
shape = readNums(file_handle, 'int32', max(num_dims, 3))[:num_dims]
else:
shape = numpy.fromfile(file_handle, dtype='int32', count=max(num_dims, 3))[:num_dims]
if debug:
logger.debug('Tensor shape, as listed in header: {0}'.format(shape))
return (elem_type, elem_size, shape)
(elem_type, elem_size, shape) = readHeader(file_handle, debug)
beginning = file_handle.tell()
num_elems = numpy.prod(shape)
result = None
if isinstance(file_handle, (gzip.GzipFile, bz2.BZ2File)):
assert (subtensor is None), 'Subtensors on gzip files are not implemented.'
result = readNums(file_handle, elem_type, (num_elems * elem_size)).reshape(shape)
elif (subtensor is None):
result = numpy.fromfile(file_handle, dtype=elem_type, count=num_elems).reshape(shape)
elif isinstance(subtensor, slice):
if (subtensor.step not in (None, 1)):
raise NotImplementedError('slice with step', subtensor.step)
if (subtensor.start not in (None, 0)):
bytes_per_row = (numpy.prod(shape[1:]) * elem_size)
file_handle.seek((beginning + (subtensor.start * bytes_per_row)))
shape[0] = (min(shape[0], subtensor.stop) - subtensor.start)
num_elems = numpy.prod(shape)
result = numpy.fromfile(file_handle, dtype=elem_type, count=num_elems).reshape(shape)
else:
raise NotImplementedError('subtensor access not written yet:', subtensor)
return result
fname = getPath(which_set)
fname = datasetCache.cache_file(fname)
file_handle = open(fname)
return parseNORBFile(file_handle, subtensor)
|
'.. todo::
WRITEME'
| def get_topological_view(self, mat=None, single_tensor=True):
| result = super(SmallNORB, self).get_topological_view(mat)
if single_tensor:
warnings.warn('The single_tensor argument is True by default to maintain backwards compatibility. This argument will be removed, and the behavior will become that of single_tensor=False, as of August 2014.')
axes = list(self.view_converter.axes)
s_index = axes.index('s')
assert (axes.index('b') == 0)
num_image_pairs = result[0].shape[0]
shape = ((num_image_pairs,) + self.view_converter.shape)
mono_shape = ((shape[:s_index] + (1,)) + shape[(s_index + 1):])
for (i, res) in enumerate(result):
logger.info('result {0} shape: {1}'.format(i, str(res.shape)))
result = tuple((t.reshape(mono_shape) for t in result))
result = numpy.concatenate(result, axis=s_index)
else:
warnings.warn('The single_tensor argument will be removed on August 2014. The behavior will be the same as single_tensor=False.')
return result
|
'Tests that the data spans [0,1]'
| def test_range(self):
| for X in [self.train.X, self.test.X]:
assert (X.min() == 0.0)
assert (X.max() == 1.0)
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| topo = self.train.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Tests that a topological batch with axes (\'c\',0,1,\'b\')
can be dimshuffled back to match the standard (\'b\',0,1,\'c\')
format.'
| def test_topo_c01b(self):
| batch_size = 100
c01b_test = MNIST(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b = c01b_test.get_topological_view(c01b_X)
assert (c01b.shape == (1, 28, 28, batch_size))
b01c = c01b.transpose(3, 1, 2, 0)
b01c_X = self.test.X[0:batch_size, :]
assert (c01b_X.shape == b01c_X.shape)
assert np.all((c01b_X == b01c_X))
b01c_direct = self.test.get_topological_view(b01c_X)
assert (b01c_direct.shape == b01c.shape)
assert np.all((b01c_direct == b01c))
|
'Tests that requesting the targets to be in IndexSpace and iterating
over them works'
| def test_y_index_space(self):
| data_specs = (IndexSpace(max_labels=10, dim=1), 'targets')
it = self.test.iterator(mode='sequential', data_specs=data_specs, batch_size=100)
for y in it:
pass
|
'Tests that requesting the targets to be in VectorSpace and iterating
over them works'
| def test_y_vector_space(self):
| data_specs = (VectorSpace(dim=10), 'targets')
it = self.test.iterator(mode='sequential', data_specs=data_specs, batch_size=100)
for y in it:
pass
|
'Compute and return the softmax transformation of sparse data.'
| def __call__(self, X):
| assert (X.ndim == 2)
return T.nnet.softmax((X * self.P))
|
'Returns as cost the mean squared
difference between the data and the models\'
output using that data.
TODO: make this a real docstring instead of
a comment appearing after the misuse of wraps'
| @wraps(Cost.expr)
def expr(self, model, data):
| (space, sources) = self.get_data_specs(model)
space.validate(data)
X = data
return T.square((model(X) - X)).mean()
|
'This loads train and test sets.'
| def setUp(self):
| skip_if_no_data()
data = stl10.STL10(which_set='train')
data = stl10.STL10(which_set='test')
|
'This tests the restrict function on each fold of the train set.'
| def test_restrict(self):
| for fold in range(10):
train = stl10.STL10(which_set='train')
stl10.restrict(train, fold)
|
'Load the train and test sets; check for nan and inf.'
| def setUp(self):
| skip_if_no_data()
self.train_set = CIFAR100(which_set='train')
self.test_set = CIFAR100(which_set='test')
assert (not np.any(np.isnan(self.train_set.X)))
assert (not np.any(np.isinf(self.train_set.X)))
assert (not np.any(np.isnan(self.test_set.X)))
assert (not np.any(np.isinf(self.test_set.X)))
|
'Test method'
| def test_adjust_for_viewer(self):
| self.train_set.adjust_for_viewer(self.train_set.X)
|
'Test method on train set'
| def test_adjust_to_be_viewed_with(self):
| self.train_set.adjust_to_be_viewed_with(self.train_set.X, np.ones(self.train_set.X.shape))
|
'Check that the train and test sets\'
get_test_set methods return same thing.'
| def test_get_test_set(self):
| train_test_set = self.train_set.get_test_set()
test_test_set = self.test_set.get_test_set()
assert np.all((train_test_set.X == test_test_set.X))
assert np.all((train_test_set.X == self.test_set.X))
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| topo = self.train_set.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Tests that a topological batch with axes (\'c\',0,1,\'b\')
can be dimshuffled back to match the standard (\'b\',0,1,\'c\')
format.'
| def test_topo_c01b(self):
| batch_size = 100
c01b_test = CIFAR100(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b = c01b_test.get_topological_view(c01b_X)
assert (c01b.shape == (3, 32, 32, batch_size))
b01c = c01b.transpose(3, 1, 2, 0)
b01c_X = self.test_set.X[0:batch_size, :]
assert (c01b_X.shape == b01c_X.shape)
assert np.all((c01b_X == b01c_X))
b01c_direct = self.test_set.get_topological_view(b01c_X)
assert (b01c_direct.shape == b01c.shape)
assert np.all((b01c_direct == b01c))
|
'Tests that batches returned by an iterator with topological
data_specs are the same as the ones returned by calling
get_topological_view on the dataset with the corresponding order'
| def test_iterator(self):
| batch_size = 100
b01c_X = self.test_set.X[0:batch_size, :]
b01c_topo = self.test_set.get_topological_view(b01c_X)
b01c_b01c_it = self.test_set.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(32, 32), num_channels=3, axes=('b', 0, 1, 'c')), 'features'))
b01c_b01c = b01c_b01c_it.next()
assert np.all((b01c_topo == b01c_b01c))
c01b_test = CIFAR100(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b_topo = c01b_test.get_topological_view(c01b_X)
c01b_c01b_it = c01b_test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(32, 32), num_channels=3, axes=('c', 0, 1, 'b')), 'features'))
c01b_c01b = c01b_c01b_it.next()
assert np.all((c01b_topo == c01b_c01b))
b01c_c01b_it = self.test_set.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(32, 32), num_channels=3, axes=('c', 0, 1, 'b')), 'features'))
b01c_c01b = b01c_c01b_it.next()
assert np.all((b01c_c01b == c01b_c01b))
c01b_b01c_it = c01b_test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(32, 32), num_channels=3, axes=('b', 0, 1, 'c')), 'features'))
c01b_b01c = c01b_b01c_it.next()
assert np.all((c01b_b01c == b01c_b01c))
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| train = TL_Challenge(which_set='train')
topo = train.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Load train, test, valid sets'
| def setUp(self):
| skip_if_no_data()
self.train = OCR(which_set='train')
self.valid = OCR(which_set='valid')
self.test = OCR(which_set='test')
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| topo = self.train.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Tests that a topological batch with axes (\'c\',0,1,\'b\')
can be dimshuffled back to match the standard (\'b\',0,1,\'c\')
format.'
| def test_topo_c01b(self):
| batch_size = 100
c01b_test = OCR(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b = c01b_test.get_topological_view(c01b_X)
assert (c01b.shape == (1, 16, 8, batch_size))
b01c = c01b.transpose(3, 1, 2, 0)
b01c_X = self.test.X[0:batch_size, :]
assert (c01b_X.shape == b01c_X.shape)
assert np.all((c01b_X == b01c_X))
b01c_direct = self.test.get_topological_view(b01c_X)
assert (b01c_direct.shape == b01c.shape)
assert np.all((b01c_direct == b01c))
|
'Tests that batches returned by an iterator with topological
data_specs are the same as the ones returned by calling
get_topological_view on the dataset with the corresponding order'
| def test_iterator(self):
| batch_size = 100
b01c_X = self.test.X[0:batch_size, :]
b01c_topo = self.test.get_topological_view(b01c_X)
b01c_b01c_it = self.test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(16, 8), num_channels=1, axes=('b', 0, 1, 'c')), 'features'))
b01c_b01c = b01c_b01c_it.next()
assert np.all((b01c_topo == b01c_b01c))
c01b_test = OCR(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b_topo = c01b_test.get_topological_view(c01b_X)
c01b_c01b_it = c01b_test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(16, 8), num_channels=1, axes=('c', 0, 1, 'b')), 'features'))
c01b_c01b = c01b_c01b_it.next()
assert np.all((c01b_topo == c01b_c01b))
b01c_c01b_it = self.test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(16, 8), num_channels=1, axes=('c', 0, 1, 'b')), 'features'))
b01c_c01b = b01c_c01b_it.next()
assert np.all((b01c_c01b == c01b_c01b))
c01b_b01c_it = c01b_test.iterator(mode='sequential', batch_size=batch_size, data_specs=(Conv2DSpace(shape=(16, 8), num_channels=1, axes=('b', 0, 1, 'c')), 'features'))
c01b_b01c = c01b_b01c_it.next()
assert np.all((c01b_b01c == b01c_b01c))
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| train = CIFAR10(which_set='train')
topo = train.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Tests that a topological batch with axes (\'c\',0,1,\'b\')
can be dimshuffled back to match the standard (\'b\',0,1,\'c\')
format.'
| def test_topo_c01b(self):
| batch_size = 100
c01b_test = CIFAR10(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b = c01b_test.get_topological_view(c01b_X)
assert (c01b.shape == (3, 32, 32, batch_size))
b01c = c01b.transpose(3, 1, 2, 0)
b01c_X = self.test.X[0:batch_size, :]
assert (c01b_X.shape == b01c_X.shape)
assert np.all((c01b_X == b01c_X))
b01c_direct = self.test.get_topological_view(b01c_X)
assert (b01c_direct.shape == b01c.shape)
assert np.all((b01c_direct == b01c))
|
'Tests that a topological batch has 4 dimensions'
| def test_topo(self):
| train = TFD(which_set='train')
topo = train.get_batch_topo(1)
assert (topo.ndim == 4)
|
'Tests that a topological batch with axes (\'c\',0,1,\'b\')
can be dimshuffled back to match the standard (\'b\',0,1,\'c\')
format.'
| def test_topo_c01b(self):
| test = TFD(which_set='test')
batch_size = 100
c01b_test = TFD(which_set='test', axes=('c', 0, 1, 'b'))
c01b_X = c01b_test.X[0:batch_size, :]
c01b = c01b_test.get_topological_view(c01b_X)
assert (c01b.shape == (1, 48, 48, batch_size))
b01c = c01b.transpose(3, 1, 2, 0)
b01c_X = test.X[0:batch_size, :]
assert (c01b_X.shape == b01c_X.shape)
assert np.all((c01b_X == b01c_X))
b01c_direct = test.get_topological_view(b01c_X)
assert (b01c_direct.shape == b01c.shape)
assert np.all((b01c_direct == b01c))
|
'Test that passing in the zero vector does not result in
a divide by 0'
| def test_zero_vector(self):
| dataset = DenseDesignMatrix(X=as_floatX(np.zeros((1, 1))))
preprocessor = GlobalContrastNormalization(subtract_mean=True, sqrt_bias=0.0, use_std=True)
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert isfinite(result)
|
'Test that using std_bias = 0.0 and use_norm = True
results in vectors having unit norm'
| def test_unit_norm(self):
| tol = 1e-05
num_examples = 5
num_features = 10
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(num_examples, num_features))
dataset = DenseDesignMatrix(X=X)
preprocessor = GlobalContrastNormalization(subtract_mean=False, sqrt_bias=0.0, use_std=False)
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
norms = np.sqrt(np.square(result).sum(axis=1))
max_norm_error = np.abs((norms - 1.0)).max()
tol = 3e-05
assert (max_norm_error < tol)
|
'Test on a random image if the per-processor loads and works without
anyerror and doesn\'t result in any nan or inf values'
| def test_random_image(self):
| rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(5, ((32 * 32) * 3)))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3), axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert isfinite(result)
|
'Test on zero-value image if cause any division by zero'
| def test_zero_image(self):
| X = as_floatX(np.zeros((5, ((32 * 32) * 3))))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3), axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert isfinite(result)
|
'Test if works fine withe different number of channel as argument'
| def test_channel(self):
| rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(5, ((32 * 32) * 3)))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3), axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32], channels=[1, 2])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert isfinite(result)
|
'We use a small predefined 8x5 matrix for
which we know the ZCA transform.'
| def setup(self):
| self.X = np.array([[(-10.0), 3.0, 19.0, 9.0, (-15.0)], [7.0, 26.0, 26.0, 26.0, (-3.0)], [17.0, (-17.0), (-37.0), (-36.0), (-11.0)], [19.0, 15.0, (-2.0), 5.0, 9.0], [(-3.0), (-8.0), (-35.0), (-25.0), (-8.0)], [(-18.0), 3.0, 4.0, 15.0, 14.0], [5.0, (-4.0), (-5.0), (-7.0), (-11.0)], [23.0, 22.0, 15.0, 20.0, 12.0]])
self.dataset = DenseDesignMatrix(X=as_floatX(self.X), y=as_floatX(np.ones((8, 1))))
self.num_components = (self.dataset.get_design_matrix().shape[1] - 1)
|
'Confirm that ZCA.inv_P_ is the correct inverse of ZCA.P_.
There\'s a lot else about the ZCA class that could be tested here.'
| def test_zca(self):
| preprocessor = ZCA()
preprocessor.fit(self.X)
identity = np.identity(self.X.shape[1], theano.config.floatX)
assert (preprocessor.P_.shape == (self.X.shape[1], self.X.shape[1]))
assert_allclose(np.dot(preprocessor.P_, preprocessor.inv_P_), identity, rtol=0.0001)
preprocessor = ZCA(filter_bias=0.0)
preprocessed_X = self.get_preprocessed_data(preprocessor)
assert_allclose(np.cov(preprocessed_X.transpose(), bias=1), identity, rtol=0.0001, atol=0.0001)
zca_transformed_X = np.array([[(-1.0199), (-0.1832), 1.9528, (-0.9603), (-0.8162)], [0.0729, 1.4142, 0.2529, 1.1861, (-1.0876)], [0.9575, (-1.1173), (-0.5435), (-1.4372), (-0.1057)], [0.6348, 1.1258, 0.2692, (-0.8893), 1.1669], [(-0.9769), 0.8297, (-1.8676), (-0.6055), (-0.5096)], [(-1.57), (-0.8389), (-0.0931), 0.8877, 1.6089], [0.4993, (-1.4219), (-0.3443), 0.9664, (-1.1022)], [1.4022, 0.1917, 0.3736, 0.852, 0.8456]])
assert_allclose(preprocessed_X, zca_transformed_X, rtol=0.001)
|
'Calculates the inverse of X with numpy.linalg.inv
if inv_P_ is not stored.'
| def test_zca_inverse(self):
| def test(store_inverse):
preprocessed_X = copy.copy(self.X)
preprocessor = ZCA(store_inverse=store_inverse)
dataset = DenseDesignMatrix(X=preprocessed_X, preprocessor=preprocessor, fit_preprocessor=True)
preprocessed_X = dataset.get_design_matrix()
assert_allclose(self.X, preprocessor.inverse(preprocessed_X), atol=5e-05, rtol=1e-05)
test(store_inverse=True)
test(store_inverse=False)
|
'Confirm that ZCA.fit works regardless of dtype of
data and config.floatX'
| def test_zca_dtypes(self):
| orig_floatX = config.floatX
try:
for floatX in ['float32', 'float64']:
for dtype in ['float32', 'float64']:
preprocessor = ZCA()
preprocessor.fit(self.X)
finally:
config.floatX = orig_floatX
|
'Confirms that PCA has decorrelated the input dataset and
principal components are arranged in decreasing order by variance'
| def test_apply_no_whiten(self):
| sut = PCA(self.num_components)
sut.apply(self.dataset, True)
cm = np.cov(self.dataset.get_design_matrix().T)
np.testing.assert_almost_equal((cm * (np.ones(cm.shape[0]) - np.eye(cm.shape[0]))), np.zeros((cm.shape[0], cm.shape[0])))
assert (np.diag(cm)[:(-1)] > np.diag(cm)[1:]).all()
|
'Confirms that PCA has decorrelated the input dataset and
variance is the same along all principal components and equal to one'
| def test_apply_whiten(self):
| sut = PCA(self.num_components, whiten=True)
sut.apply(self.dataset, True)
cm = np.cov(self.dataset.get_design_matrix().T)
np.testing.assert_almost_equal((cm * (np.ones(cm.shape[0]) - np.eye(cm.shape[0]))), np.zeros((cm.shape[0], cm.shape[0])))
np.testing.assert_almost_equal(np.diag(cm), np.ones(cm.shape[0]))
|
'Checks whether PCA performs dimensionality reduction'
| def test_apply_reduce_num_components(self):
| sut = PCA((self.num_components - 1), whiten=True)
sut.apply(self.dataset, True)
assert (self.dataset.get_design_matrix().shape[1] == (self.num_components - 1))
|
'Attempts to load train and test'
| def setUp(self):
| skip_if_no_data()
self.train = MNIST_rotated_background(which_set='train')
self.test = MNIST_rotated_background(which_set='test')
|
'This runs tests on the foveate/defoveate channel
process for different sizes of input'
| def test_transform(self):
| image = np.random.randn(1, 20, 20)
rings = [5, 2]
encoded_size = get_encoded_size(image.shape[1], image.shape[2], rings)
assert (encoded_size == 64), 'Different from previously computed value'
self.foveate_defoveate_channel(image, rings, encoded_size)
rec_image = np.random.randn(1, 70, 42)
rec_rings = [7, 4, 2]
rec_encoded_size = get_encoded_size(rec_image.shape[1], rec_image.shape[2], rec_rings)
assert (rec_encoded_size == 834), 'Not previously computed value'
self.foveate_defoveate_channel(rec_image, rec_rings, rec_encoded_size)
rec_image = np.random.randn(3, 70, 42)
rec_rings = [7, 4, 2]
rec_encoded_size = get_encoded_size(rec_image.shape[1], rec_image.shape[2], rec_rings)
assert (rec_encoded_size == 834), 'Not previously computed value'
self.foveate_defoveate_channel(rec_image, rec_rings, rec_encoded_size, bs=rec_image.shape[0])
|
'Helper function
Parameters
image :
numpy matrix in format (batch, rows, cols, chans)
rings :
list of ring_sizes used to generate compressed image
encoded_size :
number of pixels in encoded images, output of get_encoded
_size
bs :
batch size
Notes
Here we foveate the image, which reduces the quality of the rings
Defoveate it back into the original image, and see if we
once again refoveate whether it returns to the original image'
| def foveate_defoveate_channel(self, image, rings, encoded_size, bs=1):
| output = np.zeros((bs, encoded_size))
foveate_channel(image, rings, output, 0)
defoveate_channel(image, rings, output, 0)
refoveated_output = np.zeros((bs, encoded_size))
foveate_channel(image, rings, refoveated_output, 0)
np.testing.assert_allclose(refoveated_output, output)
|
'Try to encode and decode to get back the same value'
| def test_encode_decode(self):
| topo_X = np.random.randn(1, 20, 25, 5)
rings = [5]
output = encode(topo_X, rings)
reconstruct = decode(output, (20, 25, 5), rings)
np.testing.assert_allclose(encode(reconstruct, rings), output)
|
'Test to see if the RetinaCodingViewConverter loads using the
typically shape in ../norb_small.py'
| def test_RetinaCodingViewConverter(self):
| view_converter = RetinaCodingViewConverter((96, 96, 2), (8, 4, 2, 2))
image = np.random.rand(1, 96, 96, 2)
design_mat = view_converter.topo_view_to_design_mat(image)
reconstruct = view_converter.design_mat_to_topo_view(design_mat)
np.testing.assert_allclose(view_converter.topo_view_to_design_mat(reconstruct), design_mat)
|
'.. todo::
WRITEME'
| def get_design_matrix(self):
| return self.X
|
'Method inherited from Dataset'
| @wraps(Dataset.get_batch_design)
def get_batch_design(self, batch_size, include_labels=False):
| self.iterator(mode='shuffled_sequential', batch_size=batch_size, num_batches=None)
return self.next()
|
'Method inherited from Dataset'
| @wraps(Dataset.get_batch_topo)
def get_batch_topo(self, batch_size):
| raise NotImplementedError('Not implemented for sparse dataset')
|
'.. todo::
WRITEME'
| def __iter__(self):
| return self
|
'.. todo::
WRITEME'
| def next(self):
| indx = self.subset_iterator.next()
try:
mini_batch = self.X[indx]
except IndexError as e:
reraise_as(ValueError(('Index out of range' + str(e))))
return mini_batch
|
'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
|
'Returns
data : numpy matrix or 2-tuple of matrices
Returns all the data, as it is internally stored.
The definition and format of these data are described in
`self.get_data_specs()`.'
| def get_data(self):
| if (self.y is None):
return self.X
else:
return (self.X, self.y)
|
'.. todo::
WRITEME'
| def get_test_set(self):
| return self.__class__(which_set='test', split=self.split)
|
'Load ICML07 Rotated MNIST with background dataset.
Parameters
which_set : \'train\', \'valid\', \'test\'
Choose a dataset
split : (n_train, n_valid, n_test)
Choose a split into train, validateion and test datasets
Default split: 10000 training, 2000 validation and 10000 in test
dataset.'
| def __init__(self, which_set, split=(10000, 2000, 10000)):
| super(MNIST_rotated_background, self).__init__('mnist_rotated_background_images', which_set, split)
|
'Load ICML07 Convex shapes dataset.
Parameters
which_set : \'train\', \'valid\', \'test\'
Choose a dataset
split : (n_train, n_valid, n_test)
Choose a split into train, validateion and test datasets
Default split: 6000 training, 2000 validation and 50000 in test
dataset.'
| def __init__(self, which_set, split=(6000, 2000, 50000)):
| super(Convex, self).__init__('convex', which_set, split)
|
'Load ICML07 Rectangle dataset:
Parameters
which_set : \'train\', \'valid\', \'test\'
Choose a dataset
split : (n_train, n_valid, n_test)
Choose a split into train, validateion and test datasets
Default split: 1000 training, 200 validation and 50000 in test dataset.'
| def __init__(self, which_set, split=(1000, 200, 50000)):
| super(Rectangles, self).__init__('rectangles', which_set, split)
|
'Load ICML07 Rectangles/images dataset:
Parameters
which_set : \'train\', \'valid\', \'test\'
Choose a dataset
split : (n_train, n_valid, n_test)
Choose a split into train, validateion and test datasets
Default split: 10000 training, 2000 validation and 50000 in test
dataset.'
| def __init__(self, which_set, split=(10000, 2000, 50000)):
| super(RectanglesImage, self).__init__('rectangles_images', which_set, split)
|
'Sanity checks for X_labels and y_labels.
Since the np.all test used for these labels does not work with HDF5
datasets, we issue a warning that those values are not checked.'
| 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.load_all:
assert np.all((self.X < self.X_labels))
else:
warnings.warn(('HDF5Dataset cannot perform test np.all(X < ' + 'X_labels). Use X_labels at your own risk.'))
if (self.y_labels is not None):
assert (self.y is not None)
assert (self.y.ndim <= 2)
if self.load_all:
assert np.all((self.y < self.y_labels))
else:
warnings.warn(('HDF5Dataset cannot perform test np.all(y < ' + 'y_labels). Use y_labels at your own risk.'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.