Manually run this notebooks on all targets


In [656]:
target = 'Dog_1'

In [657]:
%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

In [658]:
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 [659]:
FEATURES = 'gen-8.5_medianwindow-bands2-usf-w60-b0.2-b4-b8-b12-b30-b70-0.1-0.5-0.9'

In [660]:
LOCAL_HOSTNAME=!hostname
if LOCAL_HOSTNAME[0].startswith('ip-'):
    !aws s3 cp s3://udikaggle/sezure/{FEATURES}.tgz data-cache/
    !tar xfz data-cache/{FEATURES}.tgz

each target receive a different model

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


In [661]:
pdata = read_data(target, 'preictal', FEATURES)
Np, NF = pdata.X.shape
Np, NF


Out[661]:
(184, 240)

negative examples


In [662]:
ndata = read_data(target, 'interictal', FEATURES)
Nn, NF = ndata.X.shape
Nn, NF


Out[662]:
(3680, 240)

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


In [663]:
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

In [664]:
psegments = getsegments(pdata)
Nps = len(psegments)
nsegments = getsegments(ndata)
Nns = len(nsegments)

statistics


In [665]:
npratio = float(Nn)/Np
print target,1/(1+npratio),Np,Nn
npsratio = float(Nns)/Nps
print target,1/(1+npsratio),Nps,Nns
Ntrainps = 1
Ntrainns = int(Ntrainps*npsratio)
Ntrainns


Dog_1 0.047619047619 184 3680
Dog_1 0.047619047619 4 80
Out[665]:
20

In [666]:
X = np.concatenate((pdata.X, ndata.X))
y = np.zeros(X.shape[0])
y[:pdata.X.shape[0]] = 1
nsegments = [[s+Np for s in ns] for ns in nsegments]

In [667]:
latencies = np.concatenate((pdata.latencies,ndata.latencies))

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


Out[668]:
(3864, 240)

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 [669]:
from sklearn.ensemble import RandomForestClassifier

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


Out[669]:
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 [670]:
rf.oob_score_


Out[670]:
0.95238095238095233

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


Out[671]:
[<matplotlib.lines.Line2D at 0x11ad11350>]

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 [672]:
!rm ../data-cache/X.mmap
mmX = np.memmap('../data-cache/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 [673]:
#!sleep 30

In [674]:
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[674]:
8

copy some information to all engines


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

load the shared memory on all engines


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

In [677]:
%%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 [678]:
%%px
from gradient_boost_loss import NAUC 
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.ensemble import GradientBoostingClassifier 
            est = GradientBoostingClassifier()
            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)

            nf = int(args['nf'])
            est.fit(X_trn[:,:nf], y_trn)
            
            y_train = est.predict_proba(X_trn[:,:nf])[:,1]
            y_validate = est.predict_proba(X_val[:,:nf])[:,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, args
            from hyperopt import STATUS_OK
            return {'loss':1.-validate_score, 'status':STATUS_OK, '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', 10)
    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 [679]:
%%px
from hyperopt import hp
from math import log
space = {
    'n_estimators': 1000,
    'pratio': 1,
    'learning_rate': hp.loguniform('learning_rate', np.log(0.01), np.log(1.)),
    'nf': hp.quniform( 'nf', 10, NF, 1),
    'max_features': hp.quniform( 'max_features', 10, 30, 1),
    'max_depth': hp.quniform( 'max_depth', 2, 18, 1),
    'min_samples_leaf': hp.quniform( 'min_samples_leaf', 2, 30, 1),
#     'subsample': hp.uniform( 'subsample', 0.2, 0.9),
}

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

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


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


[stderr:5] 
/Users/udi/anaconda/lib/python2.7/site-packages/sklearn/ensemble/gradient_boosting.py:397: RuntimeWarning: overflow encountered in double_scalars
  tree.value[leaf, 0, 0] = numerator / denominator
/Users/udi/anaconda/lib/python2.7/site-packages/sklearn/ensemble/gradient_boosting.py:371: RuntimeWarning: invalid value encountered in multiply
  return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))
Out[0:102]: 
{'learning_rate': 0.022826489171967838,
 'max_depth': 10.0,
 'max_features': 23.0,
 'min_samples_leaf': 19.0,
 'nf': 179.0}
Out[1:102]: 
{'learning_rate': 0.7314357184140008,
 'max_depth': 9.0,
 'max_features': 22.0,
 'min_samples_leaf': 7.0,
 'nf': 65.0}
Out[2:102]: 
{'learning_rate': 0.05334526725871157,
 'max_depth': 3.0,
 'max_features': 16.0,
 'min_samples_leaf': 16.0,
 'nf': 174.0}
Out[3:102]: 
{'learning_rate': 0.024494974453583774,
 'max_depth': 4.0,
 'max_features': 23.0,
 'min_samples_leaf': 30.0,
 'nf': 75.0}
Out[4:102]: 
{'learning_rate': 0.016763857399279505,
 'max_depth': 4.0,
 'max_features': 28.0,
 'min_samples_leaf': 5.0,
 'nf': 94.0}
Out[5:102]: 
{'learning_rate': 0.7140129597488567,
 'max_depth': 2.0,
 'max_features': 21.0,
 'min_samples_leaf': 10.0,
 'nf': 145.0}
Out[6:102]: 
{'learning_rate': 0.05561432240316577,
 'max_depth': 11.0,
 'max_features': 13.0,
 'min_samples_leaf': 14.0,
 'nf': 55.0}
Out[7:102]: 
{'learning_rate': 0.3030161471276105,
 'max_depth': 2.0,
 'max_features': 14.0,
 'min_samples_leaf': 12.0,
 'nf': 20.0}

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 [682]:
!sort -n -r ../data-cache/hyperopt.txt > ../data-cache/hyperopt.sort.txt
!head -n 5 ../data-cache/hyperopt.sort.txt


0.978520793951 1.0 {'n_estimators': 1000, 'pratio': 1, 'max_features': 16.0, 'learning_rate': 0.05334526725871157, 'max_depth': 3.0, 'nf': 174.0, 'min_samples_leaf': 16.0}
0.974787334594 1.0 {'n_estimators': 1000, 'pratio': 1, 'max_features': 11.0, 'learning_rate': 0.052284857509877845, 'max_depth': 2.0, 'nf': 222.0, 'min_samples_leaf': 3.0}
0.973393194707 1.0 {'n_estimators': 1000, 'pratio': 1, 'max_features': 27.0, 'learning_rate': 0.07488486346245497, 'max_depth': 2.0, 'nf': 217.0, 'min_samples_leaf': 26.0}
0.972188090737 1.0 {'n_estimators': 1000, 'pratio': 1, 'max_features': 29.0, 'learning_rate': 0.11225725099695992, 'max_depth': 2.0, 'nf': 222.0, 'min_samples_leaf': 26.0}
0.971975425331 1.0 {'n_estimators': 1000, 'pratio': 1, 'max_features': 25.0, 'learning_rate': 0.06734604473269949, 'max_depth': 3.0, 'nf': 217.0, 'min_samples_leaf': 22.0}

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


Out[683]:
763

Predicition/Bagging/Validation


In [684]:
tdata = read_data(target, 'test', FEATURES)
Nt, NFF = tdata.X.shape
Nt, NFF


Out[684]:
(502, 240)

In [685]:
!rm /tmp/Xt.mmap
Xt_shape = (tdata.X.shape[0], NF)
mmXt = np.memmap('../data-cache/Xt.mmap', shape=Xt_shape, dtype=np.float32, mode='w+')
mmXt[:,:] = tdata.X[:,pn_importance_order]
del mmXt # flush to disk


rm: /tmp/Xt.mmap: No such file or directory

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

In [687]:
%%px
Xt = np.memmap('../data-cache/Xt.mmap', shape=Xt_shape, dtype=np.float32, mode='r')

In [688]:
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.ensemble import GradientBoostingClassifier 
    est = GradientBoostingClassifier()

    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, y_trn)

        y_val_est = est.predict_proba(X_val)[:,1]
        
        y_test_est = est.predict_proba(X_test)[:,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 [689]:
!rm ../data-cache/validate.spkl
!rm ../data-cache/{target}_test.spkl

In [690]:
args_list = []
for res in hyeropt_results:
    args = res[2]
    print args
    args_list.append(args)
    if len(args_list) >= 16:
        break
len(args_list)


{'learning_rate': 0.05334526725871157, 'nf': 174.0, 'min_samples_leaf': 16.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 16.0, 'max_depth': 3.0}
{'learning_rate': 0.052284857509877845, 'nf': 222.0, 'min_samples_leaf': 3.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 11.0, 'max_depth': 2.0}
{'learning_rate': 0.07488486346245497, 'nf': 217.0, 'min_samples_leaf': 26.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 27.0, 'max_depth': 2.0}
{'learning_rate': 0.11225725099695992, 'nf': 222.0, 'min_samples_leaf': 26.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 29.0, 'max_depth': 2.0}
{'learning_rate': 0.06734604473269949, 'nf': 217.0, 'min_samples_leaf': 22.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 25.0, 'max_depth': 3.0}
{'learning_rate': 0.11091771632280131, 'nf': 197.0, 'min_samples_leaf': 27.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 28.0, 'max_depth': 2.0}
{'learning_rate': 0.038724644390612684, 'nf': 210.0, 'min_samples_leaf': 21.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 24.0, 'max_depth': 3.0}
{'learning_rate': 0.06511729538365887, 'nf': 178.0, 'min_samples_leaf': 18.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 21.0, 'max_depth': 3.0}
{'learning_rate': 0.183825726273952, 'nf': 157.0, 'min_samples_leaf': 29.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 15.0, 'max_depth': 3.0}
{'learning_rate': 0.13187138366127654, 'nf': 163.0, 'min_samples_leaf': 19.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 19.0, 'max_depth': 2.0}
{'learning_rate': 0.16127506098947533, 'nf': 194.0, 'min_samples_leaf': 26.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 27.0, 'max_depth': 2.0}
{'learning_rate': 0.040411449820212476, 'nf': 236.0, 'min_samples_leaf': 20.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 29.0, 'max_depth': 2.0}
{'learning_rate': 0.09040914680184965, 'nf': 232.0, 'min_samples_leaf': 26.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 28.0, 'max_depth': 2.0}
{'learning_rate': 0.08522951820841972, 'nf': 181.0, 'min_samples_leaf': 13.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 26.0, 'max_depth': 3.0}
{'learning_rate': 0.030050290129241226, 'nf': 209.0, 'min_samples_leaf': 9.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 13.0, 'max_depth': 3.0}
{'learning_rate': 0.09329387466127517, 'nf': 201.0, 'min_samples_leaf': 13.0, 'n_estimators': 1000, 'pratio': 1, 'max_features': 22.0, 'max_depth': 3.0}
Out[690]:
16

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

In [692]:
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.933754725898
0.681498109641
0.806923440454
0.800543478261
0.961153119093
0.804619565217
0.709463610586
0.898239603025
0.846065689981
0.904005198488
0.621030245747
0.740879017013
0.756557183365
0.657974952741
0.58034026465
0.645782136106
0.668643667297
0.816020793951
0.664933837429
0.874279300567
0.689142249527
0.831970699433
0.583069470699
0.881214555766
0.788350661626
0.742556710775
0.487689035917
0.868998109641
0.766564272212
0.69734168242
0.808754725898
0.883211247637
0.58540879017
0.770061436673
0.726063327032
0.864945652174
0.650224480151
0.879595935728
0.709652646503
0.933270321361
0.546042060491
0.738232514178
0.884735349716
0.716587901701
0.884073724008
0.892781190926
0.824362003781
0.937062854442
0.970061436673
0.823558601134
0.941434310019
0.804217863894
0.725827032136
0.901618620038
0.662570888469
0.867922967864
0.794210775047
0.660479678639
0.686696597353
0.614413988658
0.670557655955
0.651677693762
0.698428638941
0.588492438563
0.912157372401
0.821526465028
0.634617202268
0.893927221172
0.791469754253
0.966209829868
0.843903591682
0.738764177694
0.502622873346
0.845675803403
0.722566162571
0.880210302457
0.750933364839
0.652292060491
0.96963610586
0.590536389414
0.804879489603
0.716268903592
0.914177693762
0.951110586011
0.84109168242
0.927646502836
0.959286389414
0.841989603025
0.819116257089
0.819966918715
0.879418714556
0.716623345936
0.430281190926
0.638953213611
0.680316635161
0.654040642722
0.769104442344
0.9654536862
0.715359168242
0.846172022684
0.70177221172
0.655470226843
0.862925330813
0.612712665406
0.699810964083
0.676689508507
0.602835538752
0.837381852552
0.937807183365
0.711838374291
0.86190926276
0.863586956522
0.569470699433
0.692509451796
0.919517958412
0.86099952741
0.907655954631
0.660775047259
0.628449905482
0.647518903592
0.671301984877
0.829879489603
0.852032136106
0.581911625709
0.797093572779
0.872956049149
0.952670132325
0.639780245747
stopped

In [693]:
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 [694]:
np.sum(y_count == 0)


Out[694]:
0

In [695]:
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[695]:
0.73771701388888611

In [696]:
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 140926-GBC-combine