Last active
July 12, 2024 13:50
-
-
Save pmbaumgartner/e5553463ff9a0df5fe35bb2d635cf37d to your computer and use it in GitHub Desktop.
Create a soft label classifier from any scikit-learn regressor object
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 | |
from scipy.special import expit, logit | |
class SoftLabelClassifier(BaseEstimator, ClassifierMixin): | |
def __init__(self, regressor, eps=0.001): | |
self.regressor = regressor | |
self.eps = eps | |
def fit(self, X, y=None): | |
y = np.array(y) | |
# 1 or 0 will give us inf of -inf | |
y[y == 1.0] = 1 - self.eps | |
y[y == 0.0] = self.eps | |
y_logit = logit(y) | |
self.regressor.fit(X, y_logit) | |
def predict(self, X, y=None): | |
preds_regression = self.regressor.predict(X) | |
preds = expit(preds_regression) > 0.5 | |
return preds | |
def predict_proba(self, X, y=None): | |
preds_regression = self.regressor.predict(X) | |
preds = expit(preds_regression) | |
return preds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I had a multi-class problem (≥3 classes), how would I proceed?