Created
March 6, 2021 23:15
-
-
Save sshh12/05915e9dac761ea4903bacfebaee823b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.base import BaseEstimator, ClassifierMixin | |
import numpy as np | |
class DelphiClassifier(BaseEstimator, ClassifierMixin): | |
def __init__(self, base_clfs, output_model=None, rounds=3): | |
self.base_clfs = base_clfs | |
self.output_model = output_model | |
self.rounds = rounds | |
self.round_clfs = {} | |
def fit(self, X, y): | |
prev_results = None | |
for r in range(self.rounds): | |
results = np.empty((len(X), len(self.base_clfs))) | |
for i, (name, model) in enumerate(self.base_clfs): | |
if r == 0: | |
X_round = X | |
else: | |
X_round = np.hstack([X, prev_results]) | |
round_model = clone(model).fit(X_round, y) | |
self.round_clfs[(name, r)] = round_model | |
results[:, i] = round_model.predict_proba(X_round)[:, 1] | |
prev_results = results | |
return self | |
def _run_rounds(self, X, proba_last=False): | |
for r in range(self.rounds): | |
results = np.empty((len(X), len(self.base_clfs))) | |
for i, (name, model) in enumerate(self.base_clfs): | |
if r == 0: | |
X_round = X | |
else: | |
X_round = np.hstack([X, prev_results]) | |
model = self.round_clfs[(name, r)] | |
if r == self.rounds - 1: | |
if name == self.output_model or self.output_model is None: | |
continue | |
if proba_last: | |
return model.predict_proba(X_round) | |
else: | |
return model.predict(X_round) | |
else: | |
results[:, i] = model.predict_proba(X_round)[:, 1] | |
prev_results = results | |
def predict(self, X): | |
return self._run_rounds(X) | |
def predict_proba(self, X): | |
return self._run_rounds(X, proba_last=True) |
Author
sshh12
commented
Mar 6, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment