-
Notifications
You must be signed in to change notification settings - Fork 19.6k
feat: Add a predict_proba method on SKLearnClassifier #21556
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 6 commits
0157175
78b9370
eef00dc
1c8f4f8
c47e956
b5f809e
6540334
359e5d0
437eb7f
4bb5936
8dc1345
5cd54c6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ | |
from keras.src.wrappers.fixes import type_of_target | ||
from keras.src.wrappers.utils import TargetReshaper | ||
from keras.src.wrappers.utils import _check_model | ||
from keras.src.wrappers.utils import _estimator_has | ||
from keras.src.wrappers.utils import assert_sklearn_installed | ||
|
||
try: | ||
|
@@ -278,6 +279,15 @@ def dynamic_model(X, y, loss, layers=[10]): | |
``` | ||
""" | ||
|
||
@sklearn.utils._available_if.available_if(_estimator_has("predict_proba")) | ||
def predict_proba(self, X): | ||
|
||
"""Predict class probabilities of the input samples X.""" | ||
divakaivan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
from sklearn.utils.validation import check_is_fitted | ||
|
||
check_is_fitted(self) | ||
X = _validate_data(self, X, reset=False) | ||
return self.model_.predict(X) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. are these probabilities? Or is this more of a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Reproducible example in google colabfrom tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
import random
import numpy as np
import tensorflow as tf
random.seed(42)
np.random.seed(42)
X, y = make_classification(n_samples=1000, n_features=10, n_informative=4, n_classes=4, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
inp = Input(shape=(10,))
x = Dense(20, activation="relu")(inp)
x = Dense(20, activation="relu")(x)
x = Dense(20, activation="relu")(x)
logits_output = Dense(4, activation=None)(x)
model_logits = Model(inp, logits_output)
model_logits.compile(loss=SparseCategoricalCrossentropy(from_logits=True), optimizer="adam")
model_logits.fit(X_train, y_train, epochs=10, verbose=0)
softmax_output = tf.keras.layers.Activation('softmax')(logits_output)
model_softmax = Model(inp, softmax_output)
test_sample = X_test[:1]
print("LOGITS OUTPUT:")
pred_logits = model_logits.predict(test_sample, verbose=0)
print(pred_logits)
print("SOFTMAX MODEL OUTPUT:")
pred_softmax = model_softmax.predict(test_sample, verbose=0)
print(pred_softmax)
print("MANUAL SOFTMAX APPLIED TO LOGITS:")
pred_manual_softmax = tf.nn.softmax(pred_logits).numpy()
print(pred_manual_softmax)
print("DIFFERENCE")
print(np.abs(pred_softmax - pred_manual_softmax))
|
||
|
||
def _process_target(self, y, reset=False): | ||
"""Classifiers do OHE.""" | ||
target_type = type_of_target(y, raise_unknown=True) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -32,6 +32,21 @@ def _check_model(model): | |
) | ||
|
||
|
||
def _estimator_has(attr): | ||
|
||
def check(self): | ||
from sklearn.utils.validation import check_is_fitted | ||
|
||
check_is_fitted(self) | ||
divakaivan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return ( | ||
True | ||
if self.model_.layers[-1].activation.__name__ | ||
in ("sigmoid", "softmax") | ||
else False | ||
) | ||
divakaivan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
return check | ||
|
||
|
||
class TargetReshaper(TransformerMixin, BaseEstimator): | ||
"""Convert 1D targets to 2D and back. | ||
|
||
|
Uh oh!
There was an error while loading. Please reload this page.