<s> from __future__ import print_function <EOL> __author__ = "<STR_LIT>" <EOL> from scipy import median <EOL> class AdaptiveResampler ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , f , batchsize , update_factor = <NUM_LIT> , threshold = <NUM_LIT> , max_resampling = None ) : <EOL> self . f = f <EOL> self . batchsize = batchsize <EOL> self . update_factor = update_factor <EOL> self . threshold = threshold <EOL> self . max_resampling = max_resampling <EOL> self . recents = [ None ] * self . batchsize <EOL> self . resample_over = <NUM_LIT:1> <EOL> self . num_evals = <NUM_LIT:0> <EOL> def __call__ ( self , x ) : <EOL> res = median ( [ self . f ( x ) for _ in range ( int ( self . resample_over ) ) ] ) <EOL> if self . num_evals % self . batchsize == <NUM_LIT:0> and self . num_evals > <NUM_LIT:0> : <EOL> alt_res = median ( [ self . f ( x ) for _ in range ( int ( self . resample_over ) ) ] ) <EOL> self . _adaptResampling ( res , alt_res ) <EOL> res = <NUM_LIT:0.5> * res + <NUM_LIT:0.5> * alt_res <EOL> self . recents [ self . num_evals % self . batchsize ] = res <EOL> self . num_evals += <NUM_LIT:1> <EOL> return res <EOL> def _adaptResampling ( self , res , alt ) : <EOL> rc = sum ( [ ( x - res ) * ( x - alt ) < <NUM_LIT:0> for x in self . recents [ <NUM_LIT:1> : ] ] ) <EOL> if rc >= self . threshold * ( self . batchsize - <NUM_LIT:1> ) : <EOL> self . resample_over *= self . update_factor <EOL> if self . max_resampling is not None and self . resample_over > self . max_resampling : <EOL> self . resample_over = self . max_resampling <EOL> elif rc == <NUM_LIT:0> : <EOL> self . resample_over = max ( self . resample_over / self . update_factor , <NUM_LIT:1> ) <EOL> def testnes ( ) : <EOL> from pybrain . optimization . distributionbased . xnes import XNES <EOL> from scipy import ones <EOL> from random import gauss <EOL> import pylab <EOL> noise = <NUM_LIT:0.1> <EOL> x0 = ones ( <NUM_LIT:5> ) <EOL> fun = lambda x : - sum ( x ** <NUM_LIT:2> ) - gauss ( <NUM_LIT:0> , noise ) <EOL> fun2 = AdaptiveResampler ( fun , <NUM_LIT:10> ) <EOL> l = XNES ( fun , x0 , maxEvaluations = <NUM_LIT> , storeAllEvaluations = True ) <EOL> res = l . learn ( ) <EOL> print ( ( sum ( res [ <NUM_LIT:0> ] ** <NUM_LIT:2> ) ) ) <EOL> pylab . plot ( list ( map ( abs , l . _allEvaluations ) ) ) <EOL> l2 = XNES ( fun2 , x0 , maxEvaluations = <NUM_LIT> , storeAllEvaluations = True ) <EOL> res = l2 . learn ( ) <EOL> print ( ( sum ( res [ <NUM_LIT:0> ] ** <NUM_LIT:2> ) ) ) <EOL> print ( ( fun2 . resample_over ) ) <EOL> pylab . plot ( list ( map ( abs , l2 . _allEvaluations ) ) ) <EOL> pylab . semilogy ( ) <EOL> pylab . show ( ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> testnes ( ) </s>
