We will use distance between test segments computed in 140926-test-signal-jump to find sequence of segments that were likely together. Armed with this fact we can take the individual proababilities of each segment and combine it to form one probability that will be used to update the probabilites of all the segments in the sequence
the sequences are found using a greedy algoirthm that stops when a conflict is detected
the probabilities of segments should be combined by multiplying them, however this did not work well. Probably because the probabilites are not well calibrated. Taking the mean had a better effect.
Suppose you have a chain of segments: $i \in 1 \ldots N $
Each segment predicts a seizure $P_i$ or not $Q_i=1-P_i$
if a chain is negative then the probability is $\prod Q_i$ if a chain is positive the situation is more complex. There is a chance $U$ that a seizure detection even has happened and $V=1-U$ it did not. I estimate $U$ to be around $0.2$. So the probability is $\prod ( U * P_i + V*Q_i)$
or $\prod Q_i \times \Pi ( U \frac{P_i}{Q_i} +V )$
the ratio of positive to negative probability is just $r = \prod ( U \frac{P_i}{Q_i} +V )$ and probability is $1/(1+1/r)$
In [1]:
    
%matplotlib inline
from matplotlib import pylab as pl
import cPickle as pickle
import pandas as pd
import numpy as np
import os
    
individual segment probablility file
In [7]:
    
w_gb = 0.471
scores = pd.DataFrame()
scores['gb'] = pd.read_csv('../submissions/140929-target-combine.validate.1.csv', index_col='clip', squeeze=True)
scores['rf'] = pd.read_csv('../submissions/140929-target-combine.validate.2.csv', index_col='clip', squeeze=True)
scores['y_est'] = w_gb * scores['gb'] + (1.-w_gb)*scores['rf']
scores['y'] = [int(s.find('preictal') >= 0) for s in scores.index.values]
scores['post'] = scores.y_est
from sklearn.metrics import roc_auc_score
roc_auc_score(scores.y, scores.y_est)
    
    Out[7]:
In [8]:
    
targets = set(['_'.join(f.split('_')[:2]) for f in scores.index.values])
targets
    
    Out[8]:
from 140929-validate-signal-jump
In [82]:
    
with open('../submissions/140929-validate-signal-jump.pkl', 'rb') as fp:
    results = pickle.load(fp)
    
In [75]:
    
for i in range(N):
    if next_segment[i] != -1:
        break
i
    
    Out[75]:
In [96]:
    
list(enumerate(next_segment))
    
    Out[96]:
In [87]:
    
result['next_segment']
    
    Out[87]:
In [154]:
    
for target in targets: #list(targets)[:1]:
    result = results[target]
    Np = result['preictal']
    print
    d = result['dist']
    N = d.shape[0]
    print target, N, Np
    dord = np.unravel_index(d.ravel().argsort(),d.shape)
    Nsequences = N/6
    
    # find good pairs of segments that are likely to be paired in time
    next_segment = [-1]*N
    previous_segment = [-1]*N
    for i,(s1,s2) in enumerate(np.array(dord).T):
        dist = d[s1,s2]
        if next_segment[s1] != -1:
            print i,'right conflict',dist
            break
        if previous_segment[s2] != -1:
            print i,'left conflict',dist
            break
        next_segment[s1] = s2
        previous_segment[s2] = s1
#     if i < Nsequences:
#         print 'skip'
#         continue
    # check code
    for i in range(N):
        if next_segment[i] != -1:
            assert previous_segment[next_segment[i]] == i
            
    # validate
    bad_next = bad_previous = 0
    for i in range(N):
        if next_segment[i] != -1:
            if result['next_segment'][i] != next_segment[i]:
                bad_next += 1
                print 'n%d'%i,
        if previous_segment[i] != -1:
            if result['previous_segment'][i] != previous_segment[i]:
                bad_previous += 1
                print 'p%d'%i,
    print '\nbad next', bad_next, 'bad_previous', bad_previous
    # check ideal chains
    next_segment = result['next_segment']
    previous_segment = result['previous_segment']
    # find good sequences
    sequences = []
    for i in range(N):
        if previous_segment[i] == -1 and next_segment[i] != -1:
            j = i
            sequence = [j]
            while next_segment[j] != -1:
                j = next_segment[j]
                sequence.append(j)
            sequences.append(sequence)
    len_sequences = [len(sequence) for sequence in sequences]
    print '#sequences',len(sequences), '%segments that was sequenced',sum(len_sequences)/float(N), 'longest sequence', max(len_sequences)
    #print sequences
    
    def key(s, Np=Np):
        if s < Np:
            return '%s_preictal_segment_%04d.mat'%(target,s+1)
        else:
            return '%s_interictal_segment_%04d.mat'%(target,(s-Np)+1)
        
    #compute probability for sequences
    sequences_prb = []
    for sequence in sequences:
        p0 = 1.
        q0 = 1.
        p1 =0.
        p2 = 0.
        p3 = 1.
        U = 0.001 # chance of seizure detection event in a preictal segment
        V = 1-U
        for s in sequence:
            P = scores['y_est'][key(s)]
            Q = 1.-P
            p0 *= P
            q0 *= Q
            p1 += P
            if P > p2:
                p2 = P
            p3 *= (U * P/Q + (1-U))
        p0 = p0 / (p0+q0)
        p1 = p1 / len(sequence)
        p2 = p2
        p3 = 1./(1+1./p3)
#         print p0, p1, p2, p3
        sequences_prb.append(p3)
    # fix probability for segments in sequences
    for p,sequence in zip(sequences_prb,sequences):
        # all segments in the same sequence will be assigned the same probability
        for s in sequence:
            scores['post'][key(s)] = p
    
    
In [155]:
    
roc_auc_score(scores.y, scores.post)
    
    Out[155]:
| U | AUC | 
|---|---|
| original | 0.86366 | 
| multiply (p0) | 0.81380 | 
| mean (p1) | 0.8704 | 
| max (p2) | 0.86514 | 
| 0.1 | 0.7755 | 
| 0.2 | 0.7838 | 
| 0.3 | 0.7958 | 
| 0.4 | 0.8090 | 
| 0.5 | 0.8237 | 
| 0.6 | 0.8314 | 
| 0.65 | 0.8354 | 
| 0.7 | 0.8361 | 
| 0.72 | 0.8367 | 
| 0.74 | 0.8368 | 
| 0.75 | 0.8368 | 
| 0.77 | 0.8363 | 
| 0.8 | 0.8353 | 
| 0.9 | 0.8249 | 
Ideal
| U | AUC | 
|---|---|
| original | 0.86366 | 
| multiply (p0) | 0.87727 | 
| mean (p1) | 0.89813 | 
| max (p2) | 0.90776 | 
| p1+p2/2 | 0.90600 | 
| 0.001 | 0.9006551 | 
In [19]:
    
    
In [ ]: