Demo entry 6361498

test

   

Submitted by tset on May 04, 2017 at 14:17
Language: Python 3. Code size: 1.0 kB.

import operator

import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin

class EnsembleClassifier(BaseEstimator, ClassifierMixin):
    def __init__(self, clfs, weights=None):
        self.clfs = clfs
        self.weights = weights
        
    def fit(self, X, y):
        for clf in self.clfs:
            clf.fit(X, y)
    
    def predict(self, X):
        self.classes_ = np.asarray([clf.predict(X) for clf in self.clfs])
        if self.weights:
            avg = self.predict_proba(X)
            maj = np.apply_along_axis(lambda x: max(enumerate(x), key=operator.itemgetter(1))[0], axis=1, arr=avg)
        else:
            maj = np.asarray([np.argmax(np.bincount(self.classes_[:,c])) for c in range(self.classes_.shape[1])])
        
        return maj
    
    def predict_proba(self, X):
        self.probas_ = [clf.predict_proba(X) for clf in self.clfs]
        avg = np.average(self.probas_, axis=0, weights=self.weights)
        
        return avg

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).