[docs]classMLCache:""" Implements a cache to reduce the number of trainings a grid search has to do. """def__init__(self,name):""" @param name name of the cache """self.name=nameself.cached={}self.count_={}
[docs]defcache(self,params,value):""" Caches one object. @param params dictionary of parameters @param value value to cache """key=MLCache.as_key(params)assertkeynotinself.cached,f"Key {params} already exists"self.cached[key]=valueself.count_[key]=0
[docs]defget(self,params,default=None):""" Retrieves an element from the cache. @param params dictionary of parameters @param default if not found @return value or None if it does not exists """key=MLCache.as_key(params)res=self.cached.get(key,default)ifres!=default:self.count_[key]+=1returnres
[docs]defcount(self,params):""" Retrieves the number of times an elements was retrieved from the cache. @param params dictionary of parameters @return int """key=MLCache.as_key(params)returnself.count_.get(key,0)
[docs]@staticmethoddefas_key(params):""" Converts a list of parameters into a key. @param params dictionary @return key as a string """ifisinstance(params,str):returnparamsels=[]fork,vinsorted(params.items()):ifisinstance(v,(int,float,str)):sv=str(v)elifisinstance(v,tuple):assertall(isinstance(e,(int,float,str))foreinv),f"Unable to create a key with value {k!r}:{v}"returnstr(v)elifisinstance(v,numpy.ndarray):# id(v) may have been better but# it does not play well with joblib.sv=hash(v.tobytes())elifvisNone:sv=""else:raiseTypeError(f"Unable to create a key with value {k!r}:{v!r}")els.append((k,sv))returnstr(els)
def__len__(self):""" Returns the number of cached items. """returnlen(self.cached)
[docs]defitems(self):""" Enumerates all cached items. """yield fromself.cached.items()
[docs]defkeys(self):""" Enumerates all cached keys. """yield fromself.cached.keys()
[docs]@staticmethoddefcreate_cache(name):""" Creates a new cache. @param name name @return created cache """global_cachesassertnamenotin_caches,f"cache {name!r} already exists."cache=MLCache(name)_caches[name]=cachereturncache
[docs]@staticmethoddefremove_cache(name):""" Removes a cache with a given name. @param name name """global_cachesdel_caches[name]
[docs]@staticmethoddefget_cache(name):""" Gets a cache with a given name. @param name name @return created cache """global_cachesreturn_caches[name]
[docs]@staticmethoddefhas_cache(name):""" Tells if cache *name* is present. @param name name @return boolean """global_cachesreturnnamein_caches