aあなたのケースでは、しきい値を変更することは容認され、必要な場合もあります。デフォルトの閾値は50%であるが、ビジネス上の観点からは、たとえそのようなアプリケーションを拒否するには、15%の返済不可能な確率でも十分である。
実際、クレジットスコアリングでは、一般的なモデルでデフォルトの確率を予測した後、異なる製品用語または顧客セグメントに対して異なるカットオフを設定することが一般的です(例えば、「Credit Risk Scorecards」の第9章を参照) )。
b。閾値には2つの便利な方法は、代わりに50%の任意alpha
である:
実際
- 、
predict_proba
と手動alpha
に対する閾値を、またはラッパークラスを有する(以下のコードを参照します)。モデルを再設定せずに複数のしきい値を試したい場合は、これを使用します。
- モデルを適合させる前に
class_weights
から(alpha, 1-alpha)
に変更してください。
そして今、ラッパーのサンプルコード:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.base import BaseEstimator, ClassifierMixin
X, y = make_classification(random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
class CustomThreshold(BaseEstimator, ClassifierMixin):
""" Custom threshold wrapper for binary classification"""
def __init__(self, base, threshold=0.5):
self.base = base
self.threshold = threshold
def fit(self, *args, **kwargs):
self.base.fit(*args, **kwargs)
return self
def predict(self, X):
return (self.base.predict_proba(X)[:, 1] > self.threshold).astype(int)
rf = RandomForestClassifier(random_state=1).fit(X_train, y_train)
clf = [CustomThreshold(rf, threshold) for threshold in [0.3, 0.5, 0.7]]
for model in clf:
print(confusion_matrix(y_test, model.predict(X_test)))
assert((clf[1].predict(X_test) == clf[1].base.predict(X_test)).all())
assert(sum(clf[0].predict(X_test)) > sum(clf[0].base.predict(X_test)))
assert(sum(clf[2].predict(X_test)) < sum(clf[2].base.predict(X_test)))
それは別のしきい値の出力3つの混同行列ます:
[[13 1]
[ 2 9]]
[[14 0]
[ 3 8]]
[[14 0]
[ 4 7]]
はい、私はこれを行うための唯一の方法だと思いますpredict_probaを使用して手作業でしきい値を変更する(または、あるメトリックに応じて最良のしきい値を選択する関数を作成する)ことによって、他のケースでは悪い考えかもしれませんが、この場合は間違いありません。 – amanbirs