Changeset 10 for trunk/bin


Ignore:
Timestamp:
07/13/15 19:16:30 (9 years ago)
Author:
tim
Message:

.

Location:
trunk/bin
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/bin/analyze_packets

    r5 r10  
    4444
    4545start = time.time()
     46import cProfile
     47#cProfile.run('num_probes = analyzeProbes(db)')
    4648num_probes = analyzeProbes(db)
    4749end = time.time()
  • trunk/bin/graph

    r6 r10  
    1010import json
    1111
     12import numpy
    1213import matplotlib.mlab as mlab
    1314import matplotlib.pyplot as plt
     
    8586
    8687print('packet_rtt diff median: %f' % statistics.median(diffs))
    87 print('packet_rtt diff midhinge: %f' % midhinge(diffs))
     88print('packet_rtt diff midhinge: %f' % midsummary(diffs))
    8889print('packet_rtt diff trimean: %f' % trimean(diffs))
     90print('packet_rtt diff quadsummary: %f' % quadsummary(diffs))
     91print('packet_rtt diff ubersummary: %f' % ubersummary(diffs))
    8992print('packet_rtt diff MAD: %f' % mad(diffs))
    9093print('reported diff trimean: %f' % trimean(reported_diffs))
     94print('reported diff quadsummary: %f' % quadsummary(reported_diffs))
     95print('reported diff ubersummary: %f' % ubersummary(reported_diffs))
    9196print('reported diff MAD: %f' % mad(reported_diffs))
     97
     98import cProfile
     99kresults = kfilter({},diffs)
     100#print('packet_rtt diff kfilter: ', numpy.mean(kresults['est']), kresults['var'])
     101print('packet_rtt diff kfilter: ', kresults['est'][-1], kresults['var'][-1])
     102kresults = kfilter({},reported_diffs)
     103#print('reported diff kfilter: ', numpy.mean(kresults['est']), kresults['var'][-1])
     104print('reported diff kfilter: ', kresults['est'][-1], kresults['var'][-1])
    92105
    93106
  • trunk/bin/train

    r9 r10  
    2626
    2727from nanownlib import *
     28from nanownlib.stats import *
     29from nanownlib.parallel import WorkerThreads
    2830import nanownlib.storage
    29 from nanownlib.stats import boxTest,multiBoxTest,subsample,bootstrap,bootstrap2,trimean,midhinge,midhingeTest,samples2Distributions,samples2MeanDiffs
    30 from nanownlib.parallel import WorkerThreads
     31
    3132
    3233
     
    3536#parser.add_argument('-c', dest='cases', type=str, default='{"short":10000,"long":1010000}',
    3637#                    help='JSON representation of echo timing cases. Default: {"short":10000,"long":1010000}')
     38parser.add_argument('--retrain', action='append', default=[], help='Force a classifier to be retrained.  May be specified multiple times.')
     39parser.add_argument('--retest', action='append', default=[], help='Force a classifier to be retested.  May be specified multiple times.')
    3740parser.add_argument('session_data', default=None,
    3841                    help='Database file storing session information')
    3942options = parser.parse_args()
    4043
    41            
    42 
    43 def trainBoxTest(db, unusual_case, greater, subseries_size):
    44 
     44
     45def trainBoxTest(db, unusual_case, greater, num_observations):
     46    db.resetOffsets()
     47   
    4548    def trainAux(low,high,num_trials):
    4649        estimator = functools.partial(multiBoxTest, {'low':low, 'high':high}, greater)
    47         estimates = bootstrap3(estimator, db, 'train', unusual_case, subseries_size, num_trials)
    48         null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, subseries_size, num_trials)
     50        estimates = bootstrap3(estimator, db, 'train', unusual_case, num_observations, num_trials)
     51        null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, num_observations, num_trials)
    4952
    5053        bad_estimates = len([e for e in estimates if e != 1])
     
    116119   
    117120    num_trials = 500
    118     widths = [good_width+(x/100.0) for x in range(-60,75,5) if good_width+(x/100.0) > 0.0]
     121    widths = [good_width+(x/100.0) for x in range(-70,75,5) if good_width+(x/100.0) > 0.0]
    119122    performance = []
    120123    for width in widths:
     
    124127        job_id,errors = wt.resultq.get()
    125128        fp,fn = errors
    126         performance.append(((fp+fn)/2.0, job_id, fn, fp))
     129        #performance.append(((fp+fn)/2.0, job_id, fn, fp))
     130        performance.append((abs(fp-fn), job_id, fn, fp))
    127131    performance.sort()
    128132    #pprint.pprint(performance)
     
    133137    wt.stop()
    134138    params = json.dumps({"low":best_low,"high":best_low+best_width})
    135     return {'algorithm':"boxtest",
     139    return {'trial_type':"train",
     140            'num_observations':num_observations,
     141            'num_trials':num_trials,
    136142            'params':params,
    137             'sample_size':subseries_size,
    138             'num_trials':num_trials,
    139             'trial_type':"train",
    140143            'false_positives':performance[0][3],
    141144            'false_negatives':performance[0][2]}
    142145
    143146
    144 def trainMidhinge(db, unusual_case, greater, subseries_size):
    145 
     147def trainSummary(summaryFunc, db, unusual_case, greater, num_observations):
     148    db.resetOffsets()
     149    stest = functools.partial(summaryTest, summaryFunc)
     150   
    146151    def trainAux(distance, threshold, num_trials):
    147         estimator = functools.partial(midhingeTest, {'distance':distance,'threshold':threshold}, greater)
    148         estimates = bootstrap3(estimator, db, 'train', unusual_case, subseries_size, num_trials)
    149         null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, subseries_size, num_trials)
     152        estimator = functools.partial(stest, {'distance':distance,'threshold':threshold}, greater)
     153        estimates = bootstrap3(estimator, db, 'train', unusual_case, num_observations, num_trials)
     154        null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, num_observations, num_trials)
    150155
    151156        bad_estimates = len([e for e in estimates if e != 1])
     
    158163    #determine expected delta based on differences
    159164    mean_diffs = [s['unusual_case']-s['other_cases'] for s in db.subseries('train', unusual_case)]
    160     threshold = trimean(mean_diffs)/2.0
     165    threshold = summaryFunc(mean_diffs)/2.0
    161166    #print("init_threshold:", threshold)
    162167   
     
    181186    num_trials = 500
    182187    performance = []
    183     for t in range(50,154,4):
     188    for t in range(80,122,2):
    184189        wt.addJob(threshold*(t/100.0), (good_distance,threshold*(t/100.0),num_trials))
    185190    wt.wait()
     
    187192        job_id,errors = wt.resultq.get()
    188193        fp,fn = errors
    189         performance.append(((fp+fn)/2.0, job_id, fn, fp))
     194        #performance.append(((fp+fn)/2.0, job_id, fn, fp))
     195        performance.append((abs(fp-fn), job_id, fn, fp))
    190196    performance.sort()
    191197    #pprint.pprint(performance)
     
    217223        job_id,errors = wt.resultq.get()
    218224        fp,fn = errors
    219         performance.append(((fp+fn)/2.0, job_id, fn, fp))
     225        #performance.append(((fp+fn)/2.0, job_id, fn, fp))
     226        performance.append((abs(fp-fn), job_id, fn, fp))
    220227    performance.sort()
    221228    #pprint.pprint(performance)
     
    225232    wt.stop()
    226233    params = json.dumps({'distance':best_distance,'threshold':best_threshold})
    227     return {'algorithm':"midhinge",
     234    return {'trial_type':"train",
     235            'num_observations':num_observations,
     236            'num_trials':num_trials,
    228237            'params':params,
    229             'sample_size':subseries_size,
    230             'num_trials':num_trials,
    231             'trial_type':"train",
    232238            'false_positives':performance[0][3],
    233239            'false_negatives':performance[0][2]}
    234240
    235241
    236 classifiers = {'boxtest':{'train':trainBoxTest, 'test':multiBoxTest},
    237                'midhinge':{'train':trainMidhinge, 'test':midhinge}}
     242def trainKalman(db, unusual_case, greater, num_observations):
     243    db.resetOffsets()
     244
     245    def trainAux(params, num_trials):
     246        estimator = functools.partial(kalmanTest, params, greater)
     247        estimates = bootstrap3(estimator, db, 'train', unusual_case, num_observations, num_trials)
     248        null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, num_observations, num_trials)
     249       
     250        bad_estimates = len([e for e in estimates if e != 1])
     251        bad_null_estimates = len([e for e in null_estimates if e != 0])
     252       
     253        false_negatives = 100.0*bad_estimates/num_trials
     254        false_positives = 100.0*bad_null_estimates/num_trials
     255        return false_positives,false_negatives
     256   
     257    mean_diffs = [s['unusual_case']-s['other_cases'] for s in db.subseries('train', unusual_case)]
     258    good_threshold = kfilter({},mean_diffs)['est'][-1]/2.0
     259
     260    wt = WorkerThreads(2, trainAux)
     261    num_trials = 200
     262    performance = []
     263    for t in range(90,111):
     264        params = {'threshold':good_threshold*(t/100.0)}
     265        wt.addJob(good_threshold*(t/100.0), (params,num_trials))
     266    wt.wait()
     267    while not wt.resultq.empty():
     268        job_id,errors = wt.resultq.get()
     269        fp,fn = errors
     270        #performance.append(((fp+fn)/2.0, job_id, fn, fp))
     271        performance.append((abs(fp-fn), job_id, fn, fp))
     272    performance.sort()
     273    #pprint.pprint(performance)
     274    best_threshold = performance[0][1]
     275    #print("best_threshold:", best_threshold)
     276    params = {'threshold':best_threshold}
     277
     278    wt.stop()
     279   
     280    return {'trial_type':"train",
     281            'num_observations':num_observations,
     282            'num_trials':num_trials,
     283            'params':json.dumps(params),
     284            'false_positives':performance[0][3],
     285            'false_negatives':performance[0][2]}
     286
     287   
     288    #determine expected delta based on differences
     289classifiers = {'boxtest':{'train':trainBoxTest, 'test':multiBoxTest, 'train_results':[]},
     290               'midsummary':{'train':functools.partial(trainSummary, midsummary), 'test':midsummaryTest, 'train_results':[]},
     291               #'ubersummary':{'train':functools.partial(trainSummary, ubersummary), 'test':ubersummaryTest, 'train_results':[]},
     292               'quadsummary':{'train':functools.partial(trainSummary, quadsummary), 'test':quadsummaryTest, 'train_results':[]},
     293               'kalman':{'train':trainKalman, 'test':kalmanTest, 'train_results':[]},
     294               #'_trimean':{'train':None, 'test':trimeanTest, 'train_results':[]},
     295              }
    238296
    239297
     
    242300import cProfile
    243301
    244 def trainClassifier(db, unusual_case, greater, trainer):
     302def trainClassifier(db, unusual_case, greater, classifier, retrain=False):
     303    if retrain:
     304        print("Dropping stored training results...")
     305        db.deleteClassifierResults(classifier, 'train')
     306   
     307    trainer = classifiers[classifier]['train']
    245308    threshold = 5.0 # in percent
    246     size = 4000
     309    num_obs = 1000
     310    max_obs = int(db.populationSize('train')/5)
    247311    result = None
    248     while size < db.populationSize('train')/5:
    249         size = min(size*2, int(db.populationSize('train')/5))
    250         result = trainer(db,unusual_case,greater,size)
     312    while num_obs < max_obs:
     313        num_obs = min(int(num_obs*1.5), max_obs)
     314        result = db.fetchClassifierResult(classifier, 'train', num_obs)
     315        if result != None:
     316            train_time = "(stored)"
     317        else:
     318            start = time.time()
     319            result = trainer(db,unusual_case,greater,num_obs)
     320            result['classifier'] = classifier
     321            train_time = "%f" % (time.time()-start)
     322           
    251323        error = statistics.mean([result['false_positives'],result['false_negatives']])
    252         print("subseries size: %d | error: %f | false_positives: %f | false_negatives: %f"
    253               % (size,error,result['false_positives'],result['false_negatives']))
     324        print("number of observations: %d | error: %f | false_positives: %f | false_negatives: %f | train time: %s | params: %s"
     325              % (num_obs, error, result['false_positives'],result['false_negatives'], train_time, result['params']))
     326        db.addClassifierResults(result)
     327        classifiers[classifier]['train_results'].append(result)
     328
    254329        if error < threshold:
    255330            break
    256     if result != None:
    257         db.addClassifierResults(result)
    258331
    259332    return result
     333
     334
     335
     336def testClassifier(db, unusual_case, greater, classifier, retest=False):
     337    target_error = 5.0 # in percent
     338    num_trials = 1000
     339    max_obs = int(db.populationSize('test')/5)
     340
     341    tester = classifiers[classifier]['test']
     342   
     343    def testAux(params, num_trials, num_observations):
     344        estimator = functools.partial(tester, params, greater)
     345        estimates = bootstrap3(estimator, db, 'test', unusual_case, num_observations, num_trials)
     346        null_estimates = bootstrap3(estimator, db, 'train_null', unusual_case, num_observations, num_trials)
     347
     348        bad_estimates = len([e for e in estimates if e != 1])
     349        bad_null_estimates = len([e for e in null_estimates if e != 0])
     350       
     351        false_negatives = 100.0*bad_estimates/num_trials
     352        false_positives = 100.0*bad_null_estimates/num_trials
     353        print("testAux:", num_observations, false_positives, false_negatives, params)
     354        return false_positives,false_negatives
     355
     356
     357    if retest:
     358        print("Dropping stored test results...")
     359        db.deleteClassifierResults(classifier, 'test')
     360
     361
     362    test_results = []
     363    lte = math.log(target_error/100.0)
     364    for tr in classifiers[classifier]['train_results']:
     365        db.resetOffsets()
     366        params = json.loads(tr['params'])
     367        num_obs = tr['num_observations']
     368   
     369        print("initial test")
     370        fp,fn = testAux(params, num_trials, num_obs)
     371        error = (fp+fn)/2.0
     372        print("walking up")
     373        while (error > target_error) and (num_obs < max_obs):
     374            increase_factor = 1.5 * lte/math.log(error/100.0) # don't ask how I came up with this
     375            #print("increase_factor:", increase_factor)
     376            num_obs = min(int(increase_factor*num_obs), max_obs)
     377            fp,fn = testAux(params, num_trials, num_obs)
     378            error = (fp+fn)/2.0
     379
     380        print("walking down")
     381        while (num_obs > 0):
     382            current_best = (num_obs,error,params,fp,fn)
     383            num_obs = int(0.95*num_obs)
     384            fp,fn = testAux(params, num_trials, num_obs)
     385            error = (fp+fn)/2.0
     386            if error > target_error:
     387                break
     388       
     389        test_results.append(current_best)
     390
     391    test_results.sort()
     392    best_obs,error,best_params,fp,fn = test_results[0]
     393   
     394    return {'classifier':classifier,
     395            'trial_type':"test",
     396            'num_observations':best_obs,
     397            'num_trials':num_trials,
     398            'params':best_params,
     399            'false_positives':fp,
     400            'false_negatives':fn}
    260401
    261402
     
    268409print(":", end-start)
    269410
    270 
    271 for c,funcs in classifiers.items():
     411for c in sorted(classifiers.keys()):
     412    if classifiers[c]['train'] == None:
     413        continue
    272414    start = time.time()
    273415    print("Training %s..." % c)
    274     result = trainClassifier(db, unusual_case, greater, funcs['train'])
     416    result = trainClassifier(db, unusual_case, greater, c, c in options.retrain)
    275417    print("%s result:" % c)
    276418    pprint.pprint(result)
    277419    print("completed in:", time.time()-start)
    278420
    279 sys.exit(0)
    280 
    281 start = time.time()
    282 results = trainBoxTest(db, unusual_case, greater, 6000)
    283 #db.addClassifierResults(results)
    284 print("multi box test result:")
    285 pprint.pprint(results)
    286 print(":", time.time()-start)
     421db.clearCache()
     422
     423for c in sorted(classifiers.keys()):
     424    start = time.time()
     425    print("Testing %s..." % c)
     426    result = testClassifier(db, unusual_case, greater, c, c in options.retest)
     427    print("%s result:" % c)
     428    pprint.pprint(result)
     429    classifiers[c]['test_error'] = (result['false_positives']+result['false_negatives'])/2.0
     430    print("completed in:", time.time()-start)
Note: See TracChangeset for help on using the changeset viewer.