__all__=["Space","Categorical","Real","Int","Bool"]classSpace(object):"""Basic search space describing set of possible candidate values for hyperparameter."""@propertydefdefault(self):"""Return default value of hyperparameter corresponding to this search space. This value is tried first during hyperparameter optimization."""raiseNotImplementedErrorclassSimpleSpace(Space):def__init__(self,default):self._default=default"""Non-nested search space (i.e. corresponds to a single simple hyperparameter)."""def__repr__(self):reprstr=self.__class__.__name__ifhasattr(self,"lower")andhasattr(self,"upper"):reprstr+=": lower={}, upper={}".format(self.lower,self.upper)ifhasattr(self,"value"):reprstr+=": value={}".format(self.value)returnreprstr@propertydefdefault(self):"""Return default value of hyperparameter corresponding to this search space. This value is tried first during hyperparameter optimization."""returnself._default@default.setterdefdefault(self,value):"""Set default value for hyperparameter corresponding to this search space. The default value is always tried in the first trial of HPO."""self._default=valueclassDiscreteSpace(SimpleSpace):""" Search space with the requirement of having a discrete number of options, such that it is possible to exhaust the search space. """def__len__(self)->int:"""Returns the number of unique spaces within the discrete search space."""raiseNotImplementedError
[docs]classCategorical(DiscreteSpace):"""Nested search space for hyperparameters which are categorical. Such a hyperparameter takes one value out of the discrete set of provided options. The first value in the list of options will be the default value that gets tried first during HPO. Parameters ---------- data : Space or python built-in objects the choice candidates Examples -------- >>> a = Categorical('a', 'b', 'c', 'd') # 'a' will be default value tried first during HPO """def__init__(self,*data):self.data=[*data]super().__init__(self.data[0])def__iter__(self):foreleminself.data:yieldelemdef__getitem__(self,index):returnself.data[index]def__setitem__(self,index,data):self.data[index]=datadef__len__(self):returnlen(self.data)defconvert_to_sklearn(self):returnself.datadef__repr__(self):reprstr=self.__class__.__name__+str(self.data)returnreprstr
[docs]classReal(SimpleSpace):"""Search space for numeric hyperparameter that takes continuous values. Parameters ---------- lower : float The lower bound of the search space (minimum possible value of hyperparameter) upper : float The upper bound of the search space (maximum possible value of hyperparameter) default : float (optional) Default value tried first during hyperparameter optimization log : (True/False) Whether to search the values on a logarithmic rather than linear scale. This is useful for numeric hyperparameters (such as learning rates) whose search space spans many orders of magnitude. Examples -------- >>> learning_rate = Real(0.01, 0.1, log=True) """def__init__(self,lower,upper,default=None,log=False):iflogandlower<=0:raiseAssertionError(f"lower must be greater than 0 when `log=True`. lower: {lower}")iflower>=upper:raiseAssertionError(f"lower must be less than upper. lower: {lower}, upper: {upper}")ifdefaultisNone:default=lowersuper().__init__(default=default)self.lower=lowerself.upper=upperself.log=logdefconvert_to_sklearn(self):fromscipy.statsimportloguniform,uniformifself.log:sampler=loguniform(self.lower,self.upper)else:sampler=uniform(self.lower,self.upper-self.lower)returnsampler
[docs]classInt(DiscreteSpace):"""Search space for numeric hyperparameter that takes integer values. Parameters ---------- lower : int The lower bound of the search space (minimum possible value of hyperparameter) upper : int The upper bound of the search space (maximum possible value of hyperparameter) default : int (optional) Default value tried first during hyperparameter optimization Examples -------- >>> range = Int(0, 100) """def__init__(self,lower,upper,default=None):ifdefaultisNone:default=lowersuper().__init__(default=default)self.lower=lowerself.upper=upperdefconvert_to_sklearn(self):fromscipy.statsimportrandintreturnrandint(self.lower,self.upper+1)def__len__(self):returnself.upper-self.lower+1
[docs]classBool(Int):"""Search space for hyperparameter that is either True or False. `Bool()` serves as shorthand for: `Categorical(True, False)` Examples -------- >>> pretrained = Bool() """def__init__(self):super(Bool,self).__init__(0,1)