Manually run this notebooks on all targets


In [149]:
target = 'Dog_1'

In [150]:
%matplotlib inline
from matplotlib import pylab as pl
import cPickle as pickle
import pandas as pd
import numpy as np
import os
import re
import math
import sys
import random
from collections import defaultdict

In [151]:
import sys
sys.path.append('..')
from common.data import CachedDataLoader
cached_data_loader = CachedDataLoader('../data-cache')
def read_data(target, data_type, features):
    return cached_data_loader.load('data_%s_%s_%s'%(data_type,target,features),None)

Read data


In [152]:
FEATURES = 'gen-8_allbands2-usf-w60-b0.2-b4-b8-b12-b30-b70'
FEATURES1 = 'gen-8_maxdiff-60'

nbands = 0
nwindows = 0
for p in FEATURES.split('-'):
    if p[0] == 'b':
        nbands += 1
    elif p[0] == 'w':
        nwindows = int(p[1:])

nbands -= 1
nbands, nwindows


Out[152]:
(5, 60)

each target receive a different model

positive examples. The positive examles were upsampled (using gen_ictal=-8)


In [153]:
from common.data import CachedDataLoader
cached_data_loader = CachedDataLoader('../data-cache')

def read_data(target, data_type, features=FEATURES):
    fname = 'data_%s_%s_%s'%(data_type,target,features)
    print fname
    return cached_data_loader.load(fname,None)

def process(X, X1, percentile=[0.05,0.95], nunits=2, mask_level=5000):
    N, Nf = X.shape
    print '# samples',N,'# power points', Nf
    nchannels = Nf / (nbands*nwindows)
    print '# channels', nchannels

    fix = defaultdict(int)
    newX = []
    for i in range(N):
        nw = nwindows//nunits
        windows = X[i,:].reshape((nunits,nw,-1))
        mask = X1[i,:].reshape((nunits,nw,-1)) # max value for each channel
        for j in range(nunits):
            for k in range(nchannels):
                m = mask[j,:,k] > mask_level # find large windows
                if np.any(m):
#                     print 'FIX', sum(m)
                    fix[sum(m)] += 1
                    if not np.all(m): # make sure we had at least one good window so we can re use its values
                        # replace the bands of a large windows with the mean of the bands in all other windows
                        windows[j,m,k*nbands:(k+1)*nbands] = np.mean(windows[j,~m,k*nbands:(k+1)*nbands], axis=0)
        sorted_windows = np.sort(windows, axis=1)
        features = np.concatenate([sorted_windows[:,int(p*nw),:] for p in percentile], axis=-1)
        newX.append(features.ravel())
    newX = np.array(newX)
    print sorted(fix.items())
    return newX

def getsegments(pdata):
    segments = []
    start = 0
    last_l = 0
    for i,l in enumerate(pdata.latencies):
        if l<last_l:
            segments.append(range(start,i))
            start = i
        last_l = l
    segments.append(range(start,i+1))
    return segments

def getdata():
    pdata = read_data(target, 'preictal') # positive examples
    Np, _ = pdata.X.shape
    print 'Positive examples',Np,
    psegments = getsegments(pdata)
    Nps = len(psegments)
    print 'sequences:',Nps
    

    ndata = read_data(target, 'interictal') # negative examples
    Nn, _ = ndata.X.shape
    print 'Negative',Nn,
    nsegments = getsegments(ndata)
    Nns = len(nsegments)
    print 'sequences:',Nns

    X = np.concatenate((pdata.X, ndata.X))
    print 'p-ratio',float(Np)/(Np+Nn), 'sequences p-ratio:',float(Nps)/(Nps+Nns)
    nsegments = [[s+Np for s in ns] for ns in nsegments]
    latencies = np.concatenate((pdata.latencies,ndata.latencies))

    pdata1 = read_data(target, 'preictal', FEATURES1) # positive examples
    ndata1 = read_data(target, 'interictal', FEATURES1) # negative examples
    X1 = np.concatenate((pdata1.X, ndata1.X))

    print 'Training:'
    X = process(X, X1)
    
    
    y = np.zeros(X.shape[0])
    y[:Np] = 1
    
    print 'Test:'
    tdata = read_data(target, 'test') # test examples
    tdata1 = read_data(target, 'test', FEATURES1) # test examples
    Xt = process(tdata.X, tdata1.X)
    
    return X,y,Xt,psegments,nsegments,latencies

data is broken into segments that should be taken together when splitting to training and validation


In [154]:
X,y,Xt,psegments,nsegments,latencies = getdata()


data_preictal_Dog_1_gen-8_allbands2-usf-w60-b0.2-b4-b8-b12-b30-b70
Positive examples 184 sequences: 4
data_interictal_Dog_1_gen-8_allbands2-usf-w60-b0.2-b4-b8-b12-b30-b70
Negative 480 sequences: 80
p-ratio 0.277108433735 sequences p-ratio: 0.047619047619
data_preictal_Dog_1_gen-8_maxdiff-60
data_interictal_Dog_1_gen-8_maxdiff-60
Training:
# samples 664 # power points 4800
# channels 16
[]
Test:
data_test_Dog_1_gen-8_allbands2-usf-w60-b0.2-b4-b8-b12-b30-b70
data_test_Dog_1_gen-8_maxdiff-60
# samples 502 # power points 4800
# channels 16
[]

In [155]:
N, NF = X.shape
N, NF


Out[155]:
(664, 320)

Feature Importance

Positive/Negative feature importance

I am using RF because it needs very little (hyper) parameter tuning. On purpose I am using a small depth, because I am not interested in the best prediction (which is already high) but with the feature importance after taking into account pair interactions.


In [156]:
from sklearn.ensemble import RandomForestClassifier

rf = RandomForestClassifier(n_estimators=1000, n_jobs=-1, oob_score=True, max_depth=2)
rf.fit(X, y)


Out[156]:
RandomForestClassifier(bootstrap=True, compute_importances=None,
            criterion='gini', max_depth=2, max_features='auto',
            max_leaf_nodes=None, min_density=None, min_samples_leaf=1,
            min_samples_split=2, n_estimators=1000, n_jobs=-1,
            oob_score=True, random_state=None, verbose=0)

In [157]:
rf.oob_score_


Out[157]:
0.72891566265060237

In [158]:
pnweights = rf.feature_importances_
pn_importance_order = pnweights.argsort()[::-1]
pl.plot(rf.feature_importances_[pn_importance_order])


Out[158]:
[<matplotlib.lines.Line2D at 0x114186990>]

Classification

hyperopt

we will use Gradient Boosting Classifier which usually gives better results than L1 or RF. In addition, like RF, it does not require normalization or PCA. However, unlike RF or L1 it has many hyper parameters that can effect its performance. In addition we need to decide how many features we want to use which is another hyper-parameter. Instead of manually guessing, we can use the hyperopt to do the guesing for us

we will perform several hyperopt search in parallel each running on a different bootstrap sample of the data

shared memory

The data itself is identical so there is no need to duplicate it for each process and we will use shared memory (shmem)


In [159]:
!rm /tmp/X.mmap
mmX = np.memmap('/tmp/X.mmap', shape=X.shape, dtype=np.float32, mode='w+')
mmX[:,:] = X[:,pn_importance_order]
del mmX # flush to disk

parallel

We will use ipython parallel processing infrastructure. Visit Clusters tab in the Home page of ipython and start 8 engines (or as many cores you have on your machine) from the default profile

OR you can run the command line:

ipcluster start --n=8

wait a little bit (otherwise you will get an error on next cell)


In [160]:
#!sleep 30

In [161]:
from IPython.parallel import Client
client = Client()
lv = client.load_balanced_view()
#lv.set_flags(block = False, retries = 0)
clients=client[:]
Ncores = len(clients)
Ncores


Out[161]:
8

copy some information to all engines


In [162]:
X_shape = X.shape
clients['X_shape'] = X_shape
clients['y'] = y
clients['psegments'] = psegments
clients['nsegments'] = nsegments

load the shared memory on all engines


In [163]:
%%px
import numpy as np
N, NF = X_shape
X = np.memmap('/tmp/X.mmap', shape=X_shape, dtype=np.float32, mode='r')

In [164]:
%%px
import random, itertools
def random_train_validation_split(psegments=psegments, nsegments=nsegments, N=N, pratio=1):
    """Randomly pick one positive segment for validation and a matching number of negative segments"""
    Nps = len(psegments)
    assert Nps > 1
    Nns = len(nsegments)
    assert Nns > 1
    npsratio = float(Nns)/Nps
    Ntrainps = 1
    Ntrainns = min(max(1,int(Ntrainps*npsratio+0.5)), Nns-1) # make sure we have something to train
    
    s = random.choice(psegments)
    ns = random.sample(nsegments,Ntrainns) # sequence based
    n = list(itertools.chain(*ns)) # .ravel does not work - elements of nsegments are not of equal length
    sample_validate = s + n
    random.shuffle(sample_validate)
    
    
    all_p = list(itertools.chain(*psegments))
    all_n = list(itertools.chain(*nsegments))

    testp = list(set(all_p) - set(s))
    if pratio != 1:
        testp *= pratio
#         ntestp = len(testp)
#         boot_ntestp = int(ntestp*pratio)
#         w = np.ones(ntestp)/float(ntestp)
#         testp = [testp[i] for i, n in enumerate(np.random.multinomial(boot_ntestp, w))
#                  for k in xrange(n)]
        
    testn = list(set(all_n) - set(n))
    sample_test = testp + testn
    random.shuffle(sample_test)

    return sample_test, sample_validate

We will optimize AUC


In [165]:
%%px
import os
def hyperopt_work(args):
    from lockfile import LockFile
    space = args.get('space')
    pratio = int(space['pratio'])
    sample_train, sample_validate = random_train_validation_split(pratio=pratio)    

    X_trn = X[sample_train,:]
    y_trn = y[sample_train]
    assert y_trn.mean() > 0.01 and y_trn.mean() < 0.99

    X_val = X[sample_validate,:]
    y_val = y[sample_validate]
    
    def t_est(args):
        try:
            from sklearn import svm
            from sklearn.pipeline import Pipeline
            from sklearn.preprocessing import StandardScaler
            svc_clf = svm.SVC(C=70, probability=True)
            nrm = StandardScaler()
            est = Pipeline([('norm', nrm), ('svc', svc_clf)])

            params = dict((k,int(v) if isinstance(v, float) and abs(v - int(v)) < 1e-5 else v)
                          for k, v in args.iteritems() if k not in ['nf', 'pratio'])
            est.set_params(**params)

            nf = int(args['nf'])
            est.fit(X_trn[:,:nf].copy(), y_trn)
            
            y_train = est.predict_proba(X_trn[:,:nf].copy())[:,1]
            y_validate = est.predict_proba(X_val[:,:nf].copy())[:,1]
            
            from sklearn.metrics import roc_auc_score
            train_score = roc_auc_score(y_trn, y_train)
            validate_score = roc_auc_score(y_val, y_validate)
            
            lock = LockFile('.lock')
            with lock:
                with open('../data-cache/hyperopt.txt','a') as fp:
                    print >>fp, validate_score, train_score, os.getpid(), args
            from hyperopt import STATUS_OK
            return {'loss':1.-validate_score, 'status':STATUS_OK, 'pid':os.getpid(),
                    'train_score':train_score, 'validate_score':validate_score}
        except Exception as e:
            lock = LockFile('.lock')
            with lock:
                with open('../data-cache/hyperopt.txt','a') as fp:
                    print >>fp, 'failed', e, args
            from hyperopt import STATUS_FAIL
            return {'status':STATUS_FAIL, 'loss':1.} # 'loss' is mandatory
            
    
    max_evals = args.get('max_evals', 100)
    from hyperopt import fmin, tpe, Trials
#     trials = Trials()
    best = fmin( t_est, space, algo=tpe.suggest, max_evals=max_evals) #, trials=trials)
#     import cPickle as pickle
#     lock = LockFile('.lock')
#     with lock:
#         with open('../data-cache/hyperopt.spkl','ab') as fp:
#                 pickle.dump(trials, fp, -1)
    return best

Define statistical space in which we will do our hyper-parameter search


In [166]:
%%px
from hyperopt import hp
from math import log
space = {
    'pratio': 1,
    'svc__C': hp.loguniform('svc__C', np.log(0.01), np.log(100.)),
    'svc__kernel': 'linear', #'sigmoid',# # , 'rbf']),
#     'svc__gamma': hp.lognormal('svm_gamma', 0, 1),
#     'svc__coef0': hp.lognormal('svc__coef0', 0, 1),
#     'svc__shrinking': False,
#     'svc__tol': hp.loguniform('svc__tol', np.log(1e-4), np.log(1e-2)),
    'nf': hp.quniform( 'nf', 10, NF, 1),
}

In [167]:
!rm ../data-cache/hyperopt.*

run hyperopt searches in parallel on all cores. Each hyperopt search will do 100 evaluations of the hyper parameters.


In [168]:
%%px
hyperopt_work({'space':space, 'max_evals':100})


Out[0:152]: {'nf': 22.0, 'svc__C': 0.01444454605031127}
Out[1:152]: {'nf': 16.0, 'svc__C': 0.011004493759453504}
Out[2:152]: {'nf': 18.0, 'svc__C': 0.012314140200072128}
Out[3:152]: {'nf': 168.0, 'svc__C': 0.01189213723654311}
Out[4:152]: {'nf': 276.0, 'svc__C': 16.404797368963067}
Out[5:152]: {'nf': 57.0, 'svc__C': 0.059273522584821006}
Out[6:152]: {'nf': 16.0, 'svc__C': 0.02012373027467772}
Out[7:152]: {'nf': 16.0, 'svc__C': 0.015494710665886055}

wait for the jobs to end. This will take some time. Also your computer can get really hot, so use the time to arange some cooling to it.


In [169]:
!sort -n -r ../data-cache/hyperopt.txt > ../data-cache/hyperopt.sort.txt
!head -n 5 ../data-cache/hyperopt.sort.txt


0.928260869565 0.90134863124 3079 {'svc__kernel': 'linear', 'svc__C': 0.059273522584821006, 'nf': 57.0, 'pratio': 1}
0.924275362319 0.901821658615 3079 {'svc__kernel': 'linear', 'svc__C': 0.1824011363027172, 'nf': 52.0, 'pratio': 1}
0.923007246377 0.898601046699 3079 {'svc__kernel': 'linear', 'svc__C': 0.05240363846153534, 'nf': 58.0, 'pratio': 1}
0.921739130435 0.90845410628 3079 {'svc__kernel': 'linear', 'svc__C': 0.09376531882041579, 'nf': 61.0, 'pratio': 1}
0.918297101449 0.907145732689 3079 {'svc__kernel': 'linear', 'svc__C': 0.5651165768018234, 'nf': 55.0, 'pratio': 1}

In [170]:
fp = open('../data-cache/hyperopt.sort.txt')
hyeropt_results = []
for l in fp:
    if l.startswith('failed'):
        continue
    l = l.split()
    validate_score = float(l[0])
    train_score = float(l[1])
    pid = int(l[2])
    args = eval(''.join(l[3:]))
    hyeropt_results.append((validate_score, train_score, pid, args))
fp.close()
len(hyeropt_results)


Out[170]:
800

Predicition/Bagging/Validation


In [171]:
Nt, NFF = Xt.shape
assert NF == NFF
Nt, NFF


Out[171]:
(502, 320)

In [172]:
!rm /tmp/Xt.mmap
Xt_shape = (Nt, NF)
mmXt = np.memmap('/tmp/Xt.mmap', shape=Xt_shape, dtype=np.float32, mode='w+')
mmXt[:,:] = Xt[:,pn_importance_order]
del mmXt # flush to disk

In [173]:
clients['Xt_shape'] = Xt_shape
clients['target'] = target

In [174]:
%%px
Xt = np.memmap('/tmp/Xt.mmap', shape=Xt_shape, dtype=np.float32, mode='r')

In [175]:
def predict_work(args):
    from lockfile import LockFile
    from sklearn.ensemble import GradientBoostingClassifier 
    import cPickle as pickle

    N = X_shape[0]
    NF = int(args.get('nf', X_shape[1]))
    pratio = int(args.get('pratio',1))
    # use out-of-bag samples to estimate the generalization error
    sample_train, sample_validate = random_train_validation_split(pratio=pratio)    

    X_trn = X[sample_train,:NF]
    y_trn = y[sample_train]
    
    X_val = X[sample_validate,:NF]
    y_val = y[sample_validate]
    
    X_test = Xt[:,:NF]
    

    from sklearn import svm
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import StandardScaler
    svc_clf = svm.SVC(C=70, probability=True)
    nrm = StandardScaler()
    est = Pipeline([('norm', nrm), ('svc', svc_clf)])

    params = dict((k,int(v) if isinstance(v, float) and abs(v - int(v)) < 1e-3 else v)
                          for k, v in args.iteritems() if k not in ['nf', 'pratio'])
    est.set_params(**params)
#     est.loss__ = NAUC(2)
    try:
        est.fit(X_trn.copy(), y_trn)

        y_val_est = est.predict_proba(X_val.copy())[:,1]
        
        y_test_est = est.predict_proba(X_test.copy())[:,1]

        lock = LockFile('.lock')
        with lock:
            with open('../data-cache/validate.spkl','ab') as fp:
                # in a later stage we will use the OOB samples to make predictions on all samples
                # so keep a record of the index of each OOB sample
                pickle.dump((sample_validate,y_val_est), fp, -1)
            with open('../data-cache/%s_test.spkl'%target,'ab') as fp:
                # in a later stage we will use the OOB samples to make predictions on all samples
                # so keep a record of the index of each OOB sample
                pickle.dump(y_test_est, fp, -1)
    except Exception as e:
        return e
    from sklearn.metrics import roc_auc_score
    #  (their p_ratio will be different) so this error measure is not completely accurate
    return roc_auc_score(y_val, y_val_est)

In [176]:
!rm ../data-cache/validate.spkl
!rm ../data-cache/{target}_test.spkl

In [177]:
from collections import defaultdict
pid2args_list = defaultdict(list)
for res in hyeropt_results:
    validation_score = res[0]
    test_score = res[1]
    pid = res[2]
    args = res[3]
    pid2args_list[pid].append((validation_score, args))

In [178]:
args_list = []
for v in pid2args_list.values():
    print v[1]
    for vv in v[:4]:
        args_list.append(vv[1])


(0.924275362319, {'svc__kernel': 'linear', 'svc__C': 0.1824011363027172, 'nf': 52.0, 'pratio': 1})
(0.88768115942, {'svc__kernel': 'linear', 'svc__C': 16.404797368963067, 'nf': 276.0, 'pratio': 1})
(0.90018115942, {'svc__kernel': 'linear', 'svc__C': 0.02428217248125759, 'nf': 168.0, 'pratio': 1})
(0.778804347826, {'svc__kernel': 'linear', 'svc__C': 0.01789815737414057, 'nf': 15.0, 'pratio': 1})
(0.796376811594, {'svc__kernel': 'linear', 'svc__C': 0.010561614469297568, 'nf': 13.0, 'pratio': 1})
(0.734420289855, {'svc__kernel': 'linear', 'svc__C': 0.03557220024296285, 'nf': 17.0, 'pratio': 1})
(0.723188405797, {'svc__kernel': 'linear', 'svc__C': 0.022790862901953337, 'nf': 17.0, 'pratio': 1})
(0.692028985507, {'svc__kernel': 'linear', 'svc__C': 0.03742719830581668, 'nf': 18.0, 'pratio': 1})

In [179]:
args_list


Out[179]:
[{'nf': 57.0,
  'pratio': 1,
  'svc__C': 0.059273522584821006,
  'svc__kernel': 'linear'},
 {'nf': 52.0,
  'pratio': 1,
  'svc__C': 0.1824011363027172,
  'svc__kernel': 'linear'},
 {'nf': 58.0,
  'pratio': 1,
  'svc__C': 0.05240363846153534,
  'svc__kernel': 'linear'},
 {'nf': 61.0,
  'pratio': 1,
  'svc__C': 0.09376531882041579,
  'svc__kernel': 'linear'},
 {'nf': 276.0,
  'pratio': 1,
  'svc__C': 23.111102411527316,
  'svc__kernel': 'linear'},
 {'nf': 276.0,
  'pratio': 1,
  'svc__C': 16.404797368963067,
  'svc__kernel': 'linear'},
 {'nf': 275.0,
  'pratio': 1,
  'svc__C': 0.45316867801451505,
  'svc__kernel': 'linear'},
 {'nf': 271.0,
  'pratio': 1,
  'svc__C': 13.165954917787275,
  'svc__kernel': 'linear'},
 {'nf': 168.0,
  'pratio': 1,
  'svc__C': 0.01189213723654311,
  'svc__kernel': 'linear'},
 {'nf': 168.0,
  'pratio': 1,
  'svc__C': 0.02428217248125759,
  'svc__kernel': 'linear'},
 {'nf': 169.0,
  'pratio': 1,
  'svc__C': 0.011184399766794181,
  'svc__kernel': 'linear'},
 {'nf': 172.0,
  'pratio': 1,
  'svc__C': 0.030851292060746455,
  'svc__kernel': 'linear'},
 {'nf': 16.0,
  'pratio': 1,
  'svc__C': 0.011004493759453504,
  'svc__kernel': 'linear'},
 {'nf': 15.0,
  'pratio': 1,
  'svc__C': 0.01789815737414057,
  'svc__kernel': 'linear'},
 {'nf': 22.0,
  'pratio': 1,
  'svc__C': 0.01077362311541191,
  'svc__kernel': 'linear'},
 {'nf': 24.0,
  'pratio': 1,
  'svc__C': 0.03219579622916524,
  'svc__kernel': 'linear'},
 {'nf': 22.0,
  'pratio': 1,
  'svc__C': 0.01444454605031127,
  'svc__kernel': 'linear'},
 {'nf': 13.0,
  'pratio': 1,
  'svc__C': 0.010561614469297568,
  'svc__kernel': 'linear'},
 {'nf': 14.0,
  'pratio': 1,
  'svc__C': 0.01152716206627307,
  'svc__kernel': 'linear'},
 {'nf': 11.0,
  'pratio': 1,
  'svc__C': 0.010315994744334986,
  'svc__kernel': 'linear'},
 {'nf': 16.0,
  'pratio': 1,
  'svc__C': 0.015494710665886055,
  'svc__kernel': 'linear'},
 {'nf': 17.0,
  'pratio': 1,
  'svc__C': 0.03557220024296285,
  'svc__kernel': 'linear'},
 {'nf': 15.0,
  'pratio': 1,
  'svc__C': 0.011719304857896106,
  'svc__kernel': 'linear'},
 {'nf': 15.0,
  'pratio': 1,
  'svc__C': 0.04603425987974184,
  'svc__kernel': 'linear'},
 {'nf': 18.0,
  'pratio': 1,
  'svc__C': 0.012314140200072128,
  'svc__kernel': 'linear'},
 {'nf': 17.0,
  'pratio': 1,
  'svc__C': 0.022790862901953337,
  'svc__kernel': 'linear'},
 {'nf': 11.0,
  'pratio': 1,
  'svc__C': 0.012309100981176956,
  'svc__kernel': 'linear'},
 {'nf': 11.0,
  'pratio': 1,
  'svc__C': 0.027988893623160288,
  'svc__kernel': 'linear'},
 {'nf': 16.0,
  'pratio': 1,
  'svc__C': 0.02012373027467772,
  'svc__kernel': 'linear'},
 {'nf': 18.0,
  'pratio': 1,
  'svc__C': 0.03742719830581668,
  'svc__kernel': 'linear'},
 {'nf': 13.0,
  'pratio': 1,
  'svc__C': 0.010432278778815621,
  'svc__kernel': 'linear'},
 {'nf': 12.0,
  'pratio': 1,
  'svc__C': 0.01208956011600015,
  'svc__kernel': 'linear'}]

In [180]:
results = lv.map(predict_work, args_list*Ncores)

In [181]:
import IPython
itr = results.__iter__()
while True:
    try:
        r = itr.next()
    except StopIteration:
        print 'stopped'
        break
    except IPython.parallel.error.RemoteError as e:
        print e
        continue
    except Exception as e:
        print e.__class__
        continue
    print r


0.645471014493
0.758514492754
0.54402173913
0.396376811594
0.637137681159
0.485597826087
0.721557971014
0.615942028986
0.423369565217
0.884963768116
0.882065217391
0.511956521739
0.78768115942
0.803351449275
0.580615942029
0.838405797101
0.722373188406
0.739492753623
0.68097826087
0.78115942029
0.764130434783
0.848188405797
0.83115942029
0.791123188406
0.867391304348
0.750724637681
0.732608695652
0.757789855072
0.797282608696
0.764855072464
0.71856884058
0.746557971014
0.610144927536
0.718115942029
0.438586956522
0.554166666667
0.81268115942
0.797826086957
0.771014492754
0.817391304348
0.510869565217
0.623913043478
0.452717391304
0.860144927536
0.888677536232
0.850362318841
0.778985507246
0.797101449275
0.865036231884
0.784963768116
0.688405797101
0.852898550725
0.766666666667
0.700362318841
0.797826086957
0.644202898551
0.736684782609
0.871195652174
0.720652173913
0.827626811594
0.791123188406
0.723822463768
0.544565217391
0.865760869565
0.653442028986
0.640942028986
0.876721014493
0.866485507246
0.623731884058
0.70597826087
0.50615942029
0.822463768116
0.547463768116
0.675724637681
0.709601449275
0.885416666667
0.797010869565
0.839492753623
0.861775362319
0.732065217391
0.641485507246
0.725724637681
0.705072463768
0.764492753623
0.775
0.823188405797
0.646014492754
0.845652173913
0.645471014493
0.899275362319
0.569565217391
0.775362318841
0.821920289855
0.739311594203
0.84365942029
0.713405797101
0.511956521739
0.839855072464
0.589673913043
0.851177536232
0.869565217391
0.810326086957
0.733695652174
0.84365942029
0.907155797101
0.891304347826
0.474094202899
0.687137681159
0.791123188406
0.784057971014
0.745833333333
0.817028985507
0.780434782609
0.780615942029
0.728623188406
0.722735507246
0.889402173913
0.627898550725
0.787137681159
0.821920289855
0.893115942029
0.838405797101
0.730525362319
0.798369565217
0.83134057971
0.713405797101
0.78097826087
0.722826086957
0.839855072464
0.523369565217
0.56231884058
0.710688405797
0.441847826087
0.873369565217
0.801630434783
0.748731884058
0.67518115942
0.532427536232
0.623188405797
0.760507246377
0.737137681159
0.8125
0.790217391304
0.442753623188
0.838586956522
0.771195652174
0.711413043478
0.725
0.788949275362
0.688224637681
0.818297101449
0.822916666667
0.814492753623
0.770108695652
0.658695652174
0.849637681159
0.820380434783
0.800996376812
0.846195652174
0.803804347826
0.668115942029
0.522282608696
0.662137681159
0.530797101449
0.754438405797
0.551811594203
0.786050724638
0.702173913043
0.842210144928
0.441123188406
0.634963768116
0.539492753623
0.56902173913
0.827173913043
0.878442028986
0.845108695652
0.773550724638
0.655434782609
0.745652173913
0.621920289855
0.817481884058
0.740942028986
0.730797101449
0.925543478261
0.807065217391
0.826630434783
0.841304347826
0.853804347826
0.871376811594
0.863768115942
0.792119565217
0.615579710145
0.732246376812
0.734963768116
0.566485507246
0.569112318841
0.794746376812
0.344384057971
0.447010869565
0.814130434783
0.474456521739
0.7125
0.447101449275
0.5625
0.725362318841
0.844565217391
0.727355072464
0.56268115942
0.596376811594
0.902717391304
0.739673913043
0.809782608696
0.717572463768
0.727717391304
0.869202898551
0.783333333333
0.761050724638
0.875543478261
0.748913043478
0.741032608696
0.836956521739
0.771195652174
0.815217391304
0.745652173913
0.586775362319
0.68097826087
0.748550724638
0.58143115942
0.414583333333
0.503442028986
0.570108695652
0.759239130435
0.840579710145
0.691666666667
0.238586956522
0.486956521739
0.79393115942
0.647101449275
0.729528985507
0.75606884058
0.546557971014
0.679891304348
0.740036231884
0.693297101449
0.715217391304
0.661775362319
0.702536231884
0.795289855072
0.867663043478
0.803260869565
0.512137681159
0.840851449275
0.669384057971
0.705253623188
0.69347826087
0.702536231884
stopped

In [182]:
fp = open('../data-cache/validate.spkl','rb')
count = 0
y_est = np.zeros(N)
y_count = np.zeros(N)
vals = []
while True:
    try:
        sample_validate,y_val_est = pickle.load(fp)
    except:
        break
    count += 1
    y_est[sample_validate] += y_val_est
    y_count[sample_validate] += 1

    idx = y_val_est.argsort()[::-1]
    n = len(y_val_est)
    val_recall_support = np.zeros(n)
    p_sum = 0.
    for i,j in enumerate(idx):
        p_sum += float(y[sample_validate[j]])
        val_recall_support[i] = p_sum
    val_x = np.linspace(0.,100.,n)
    vals.append((val_x, val_recall_support))

y_est /= y_count

In [183]:
np.sum(y_count == 0)


Out[183]:
0

In [184]:
from sklearn.metrics import roc_auc_score
y_no_overlap = [r for r,l in zip(y, latencies) if abs(l-int(l)) < 0.01]
y_est_no_overlap = [r for r,l in zip(y_est, latencies) if abs(l-int(l)) < 0.01]
roc_auc_score(y_no_overlap, y_est_no_overlap)


Out[184]:
0.72473958333333333

In [185]:
with open('../data-cache/%s_predict.spkl'%target,'wb') as fp:
    pickle.dump((y_no_overlap, y_est_no_overlap), fp, -1)

after running the entire notebook, again and again, on all targets - continue to 141107-GBC-combine


In [185]: