Navigation

Quick search

Enter search terms or a module, class or function name.

Source code for mlproblems.generic

# Copyright 2011 Hugo Larochelle. All rights reserved.# # Redistribution and use in source and binary forms, with or without modification, are# permitted provided that the following conditions are met:# # 1. Redistributions of source code must retain the above copyright notice, this list of# conditions and the following disclaimer.# # 2. Redistributions in binary form must reproduce the above copyright notice, this list# of conditions and the following disclaimer in the documentation and/or other materials# provided with the distribution.# # THIS SOFTWARE IS PROVIDED BY Hugo Larochelle ``AS IS'' AND ANY EXPRESS OR IMPLIED# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Hugo Larochelle OR# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# # The views and conclusions contained in the software and documentation are those of the# authors and should not be interpreted as representing official policies, either expressed# or implied, of Hugo Larochelle."""The ``mlproblems.generic`` module contains MLProblems that are notdesigned for a specific type of problem. They typically allow formanipulations that can be useful for many tasks.This module contains the following classes:* MLProblem: Root class for machine learning problems.* SubsetProblem: Extracts a subset of examples from a dataset.* KFirstProblem: Extracts a the first few (K) examples from a dataset.* SubsetFieldsProblem: Extracts a subset of the fields in a dataset.* MergedProblem: Merges several datasets together.* PreprocessedProblem: Applies an arbitrary preprocessing on a dataset.* MinibatchProblem: Puts examples of datasets into mini-batches.* SemisupervisedProblem: Removes the labels of a subset of the examples in a dataset."""importnumpyasnpimportcopy

[docs]classMLProblem:""" Root class for machine learning problems. An MLProblem consists simply in an iterator over elements in ``data``. It also has some metadata, or "data about the data". All that is assume about ``data`` is that it is possible to iterate over its content. The metadata can be given explicitly by the user in the constructor. If ``data`` is itself an MLProblem, then its metadata will also be used (with priority given to the explicitly passed metadata). **Required metadata:** * ``'length'``: Number of examples (optional, will set the output of ``__len__(self)``). """def__init__(self,data=None,metadata={},call_setup=True):self.data=dataself.metadata={}ifisinstance(data,MLProblem):# Use metadata from data if is an mlproblemself.metadata.update(data.metadata)self.__source_mlproblem__=dataelse:self.__source_mlproblem__=Noneself.metadata.update(metadata)self.__length__=Noneif'length'inself.metadata:# Gives a chance to set length through metadataself.__length__=self.metadata['length']delself.metadata['length']# So that it isn't passed to subsequent mlproblemsifcall_setup:MLProblem.setup(self)def__iter__(self):forexampleinself.data:yieldexampledef__len__(self):ifself.__length__isNone:# if metadata hasn't been used to set length, use len(data)try:returnlen(self.data)exceptAttributeError:# Figure out length with exhaustive countingprint'Warning in mlpython.mlproblems.generic.MLProblem: couldn\'t get length from len(data)... will loop over MLProblem to compute length'self.__length__=0forexampleinself:self.__length__+=1returnself.__length__else:returnself.__length__

[docs]defsetup(self):""" Adapts the MLProblem to the given data's content. For this root class, it does nothing. However, an MLProblem that would normalize examples by subtracting the data's average would compute this average in this method. """pass

[docs]defapply_on(self,new_data,new_metadata={}):""" Returns a new MLProblem that will apply on some new data the same processing that this MLProblem applies on its ``data``. For this root class, there isn't any processing to share, hence this method doesn't do much, besides calling ``data.apply_on(new_data,new_metadata)`` if ``data`` is itself an MLProblem. However, for an MLProblem that would normalize examples by subtracting the data's average, it would construct a new MLProblem such that it'll subtract the same average. """ifself.__source_mlproblem__isnotNone:new_data=self.__source_mlproblem__.apply_on(new_data,new_metadata)new_metadata={}# new_data should already contain the new_metadata, since it is an mlproblemnew_problem=self.__class__(new_data,new_metadata,call_setup=False)returnnew_problem

[docs]defpeak(self):""" Returns the first example of the MLProblem. """returnself.__iter__().next()

[docs]defraw_source(self):""" Returns the data and metadata of the first MLProblem in the series that led to this MLProblem. """ifself.__source_mlproblem__isNone:returnself.data,self.metadataelse:returnself.__source_mlproblem__.raw_source()

[docs]classSubsetProblem(MLProblem):""" Extracts a subset of the examples in a dataset. The examples that are extracted have their ID (i.e. the example number from 0 to ``len(data)-1``, as defined by the order in which the iterator yields the examples) in a given ``subset``. """def__init__(self,data=None,metadata={},call_setup=True,subset=set([])):MLProblem.__init__(self,data,metadata)self.subset=subsetifcall_setup:SubsetProblem.setup(self)def__iter__(self):id=0forexampleinself.data:ifidinself.subset:yieldexampleid+=1def__len__(self):returnlen(self.subset)defapply_on(self,new_data,new_metadata={}):# Since new_data probably doesn't use the same subset of example ids,# we either return a basic mlproblem or the output from the source mlproblemifself.__source_mlproblem__isnotNone:new_problem=self.__source_mlproblem__.apply_on(new_data,new_metadata)else:new_problem=MLProblem(new_data,new_metadata,call_setup=False)returnnew_problem

[docs]classKFirstProblem(MLProblem):""" Extracts the first few examples (K) in a dataset. This is useful to run quick experiments to debug. """def__init__(self,data=None,metadata={},call_setup=True,K=100):MLProblem.__init__(self,data,metadata)self.K=Kifcall_setup:KFirstProblem.setup(self)def__iter__(self):fori,exampleinenumerate(self.data):ifi>=self.K:breakyieldexampledef__len__(self):returnmin(self.K,len(self.data))defapply_on(self,new_data,new_metadata={}):# Since new_data probably has a different size and might require a different K,# we either return a basic mlproblem or the output from the source mlproblemifself.__source_mlproblem__isnotNone:new_problem=self.__source_mlproblem__.apply_on(new_data,new_metadata)else:new_problem=MLProblem(new_data,new_metadata,call_setup=False)returnnew_problem

[docs]classSubsetFieldsProblem(MLProblem):""" Extracts a subset of the fields in a dataset. The fields that are selected are given by option ``fields``, a list of indices corresponding to the fields to keep. Each example of the new dataset will now be a list of those fields, unless ``fields`` contains only one index, in which case each example will correspond to that field. """def__init__(self,data=None,metadata={},call_setup=True,fields=[0]):MLProblem.__init__(self,data,metadata)self.fields=fieldsifcall_setup:SubsetFieldsProblem.setup(self)def__iter__(self):forexampleinself.data:iflen(self.fields)==1:yieldexample[self.fields[0]]else:yield[example[i]foriinself.fields]defapply_on(self,new_data,new_metadata={}):ifself.__source_mlproblem__isnotNone:new_data=self.__source_mlproblem__.apply_on(new_data,new_metadata)new_metadata={}# new_data should already contain the new_metadata, since it is an mlproblemnew_problem=SubsetFieldsProblem(new_data,new_metadata,call_setup=False,fields=self.fields)returnnew_problem

[docs]classMergedProblem(MLProblem):""" Merges several datasets together. Each element of data should itself be an iterator over examples. All examples of the first dataset are first iterated over, then all examples of the second, and so on. If option ``serial`` is False, then instead of iterating over the examples of one dataset at a time, it cycles over datasets and each time returns only one example. The iterator stops when all examples in all datasets have been iterated over at least once. Notice that if the datasets don't all have the same size, then some examples will be iterated over at least twice. """def__init__(self,data=None,metadata={},call_setup=True,serial=True):self.data=dataself.metadata={}ifisinstance(data[0],MLProblem):# Use metadata from data if is an mlproblemself.metadata.update(data[0].metadata)self.__source_mlproblem__=data[0]else:self.__source_mlproblem__=Noneself.metadata.update(metadata)#self.__length__ = None#if 'length' in self.metadata: # Gives a chance to set length through metadata# self.__length__ = self.metadata['length']# del self.metadata['length'] # So that it isn't passed to subsequent mlproblemsself.serial=serialifcall_setup:MergedProblem.setup(self)def__iter__(self):ifself.serial:fordatasetinself.data:forexampleindataset:yieldexampleelse:iterated_over_once=[False]*len(self.data)# Initialize iteratorsiterators=[dataset.__iter__()fordatasetinself.data]examples=[iter.next()foriteriniterators]whilenotall(iterated_over_once):forexampleinexamples:yieldexamplefort,iterinenumerate(iterators):try:example=iter.next()exceptStopIteration:iterators[t]=self.data[t].__iter__()iterated_over_once[t]=Trueexample=iterators[t].next()examples[t]=exampledef__len__(self):ifself.serial:l=0fordatasetinself.data:l+=len(dataset)returnlelse:max_l=max([len(dataset)fordatasetinself.data])returnmax_l*len(self.data)defapply_on(self,new_data,new_metadata={}):# Since new_data is probably not a list of mlproblems, # we either return a basic mlproblem or the output from the source mlproblemifself.__source_mlproblem__isnotNone:new_problem=self.__source_mlproblem__.apply_on(new_data,new_metadata)else:new_problem=MLProblem(new_data,new_metadata,call_setup=False)returnnew_problem

[docs]classPreprocessedProblem(MLProblem):""" MLProblem that applies a preprocessing function on examples from a dataset. The examples of this MLProblem is the result of applying option ``preprocess`` on the examples in the original data. Hence, ``preprocess`` should be a callable function taking two arguments (an example from the original data as well as the metadata) and returning a preprocessed example. **IMPORANT:** if ``preprocess`` changes the size of the inputs, the metadata (i.e. ``'input_size'``) should be changed accordingly within ``preprocess``. """def__init__(self,data=None,metadata={},call_setup=True,preprocess=None):MLProblem.__init__(self,data,metadata)self.preprocess=preprocessifcall_setup:PreprocessedProblem.setup(self)# Call preprocess on first example, so that it sets the new_metadata correctlyself.__iter__().next()def__iter__(self):forexampleinself.data:yieldself.preprocess(example,self.metadata)defapply_on(self,new_data,new_metadata={}):ifself.__source_mlproblem__isnotNone:new_data=self.__source_mlproblem__.apply_on(new_data,new_metadata)new_metadata={}# new_data should already contain the new_metadata, since it is an mlproblemnew_problem=PreprocessedProblem(new_data,new_metadata,call_setup=False,preprocess=self.preprocess)# Call preprocess on first example, so that it sets the new_metadata correctlynew_problem.__iter__().next()returnnew_problem

[docs]classMinibatchProblem(MLProblem):""" MLProblem that puts examples into mini-batches. Option ``minibatch_size`` determines the size of the mini-batches. By default, this class assumes that the underlying dataset corresponds to a single field (e.g. the input). If this is not the case (e.g. contains pairs of inputs and targets), option ``has_single_field`` should be set to ``False``. If the examples don't fit evenly into mini-batches of the desired size, the last mini-batch will be filled with copies of the remaining examples. **Defined metadata:** * ``'minibatch_size'``: number of examples in each mini-batch """def__init__(self,data=None,metadata={},call_setup=True,minibatch_size=None,has_single_field=True):MLProblem.__init__(self,data,metadata)self.minibatch_size=minibatch_sizeself.has_single_field=has_single_fieldifcall_setup:MinibatchProblem.setup(self)self.metadata['minibatch_size']=self.minibatch_sizedef__len__(self):returnint(np.ceil(float(len(self.data))/self.minibatch_size))def__iter__(self):minibatch_filling_count=0forexampleinself.data:ifminibatch_filling_count==0:ifself.has_single_field:if(nothasattr(example,'shape'))orexample.shape==(1,):minibatch_container=np.zeros((self.minibatch_size,))else:minibatch_container=np.zeros((self.minibatch_size,)+example.shape)else:minibatch_container=()forfieldinexample:if(nothasattr(field,'shape'))orfield.shape==(1,):minibatch_container+=(np.zeros((self.minibatch_size,)),)else:minibatch_container+=(np.zeros((self.minibatch_size,)+field.shape),)ifself.has_single_field:minibatch_container[minibatch_filling_count]=exampleelse:forfinrange(len(minibatch_container)):minibatch_container[f][minibatch_filling_count]=example[f]minibatch_filling_count+=1ifminibatch_filling_count==self.minibatch_size:yieldminibatch_containerminibatch_filling_count=0ifminibatch_filling_count>0:ifself.has_single_field:i=0whileminibatch_filling_count<self.minibatch_size:minibatch_container[minibatch_filling_count]=minibatch_container[i]i+=1minibatch_filling_count+=1else:i=0whileminibatch_filling_count<self.minibatch_size:forfinrange(len(minibatch_container)):minibatch_container[f][minibatch_filling_count]=minibatch_container[f][i]i+=1minibatch_filling_count+=1yieldminibatch_containerdefapply_on(self,new_data,new_metadata={}):ifself.__source_mlproblem__isnotNone:new_data=self.__source_mlproblem__.apply_on(new_data,new_metadata)new_metadata={}# new_data should already contain the new_metadata, since it is an mlproblemnew_problem=MinibatchProblem(new_data,new_metadata,call_setup=False,minibatch_size=self.minibatch_size,has_single_field=self.has_single_field)returnnew_problem

[docs]classSemisupervisedProblem(MLProblem):""" Removes the labels of a subset of the examples in a dataset. The examples that have their ID (i.e. the example number from 0 to ``len(data)-1``, as defined by the order in which the iterator yields the examples) in ``unlabeled_ids`` will have their labels be replaced by None. The index of the label field can be given by option ``label_field``. """def__init__(self,data=None,metadata={},call_setup=True,unlabeled_ids=set([]),label_field=1):MLProblem.__init__(self,data,metadata)self.unlabeled_ids=unlabeled_idsself.label_field=label_fieldifcall_setup:SemisupervisedProblem.setup(self)def__iter__(self):id=0forexampleinself.data:ifidinself.unlabeled_ids:unlabeled_example=copy.deepcopy(example)unlabeled_example[self.label_field]=Noneyieldunlabeled_exampleelse:yieldexampleid+=1defapply_on(self,new_data,new_metadata={}):# Don't apply the same unlabeling to new_data.# We either return a basic mlproblem or the output from the source mlproblemifself.__source_mlproblem__isnotNone:new_problem=self.__source_mlproblem__.apply_on(new_data,new_metadata)else:new_problem=MLProblem(new_data,new_metadata,call_setup=False)returnnew_problem