Pou*_*del 7 python scikit-learn catboost
类似的问题:
Catboost 教程
在这个问题中,我有一个二元分类问题。建模后,我们得到了测试模型预测y_pred,并且我们已经有了真正的测试标签y_true。
我想获得由以下等式定义的自定义评估指标:
profit = 400 * truePositive - 200*fasleNegative - 100*falsePositive
Run Code Online (Sandbox Code Playgroud)
另外,由于利润越高越好,我想最大化该功能而不是最小化它。
如何在catboost中获取这个eval_metric?
profit = 400 * truePositive - 200*fasleNegative - 100*falsePositive
Run Code Online (Sandbox Code Playgroud)
def get_profit(y_true, y_pred):
tn, fp, fn, tp = sklearn.metrics.confusion_matrix(y_true,y_pred).ravel()
loss = 400*tp - 200*fn - 100*fp
return loss
scoring = sklearn.metrics.make_scorer(get_profit, greater_is_better=True)
Run Code Online (Sandbox Code Playgroud)
如何在catboost中完成自定义eval指标?
到目前为止我的更新
class ProfitMetric(object):
def get_final_error(self, error, weight):
return error / (weight + 1e-38)
def is_max_optimal(self):
return True
def evaluate(self, approxes, target, weight):
assert len(approxes) == 1
assert len(target) == len(approxes[0])
approx = approxes[0]
error_sum = 0.0
weight_sum = 0.0
** I don't know here**
return error_sum, weight_sum
Run Code Online (Sandbox Code Playgroud)
与你的主要区别是:
@staticmethod
def get_profit(y_true, y_pred):
y_pred = expit(y_pred).astype(int)
y_true = y_true.astype(int)
#print("ACCURACY:",(y_pred==y_true).mean())
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
loss = 400*tp - 200*fn - 100*fp
return loss
Run Code Online (Sandbox Code Playgroud)
从您链接的预测是什么的示例中并不明显,但经过检查后发现,它catboost在内部将预测视为原始对数赔率(帽子提示@Ben)。因此,要正确使用,confusion_matrix您需要确保y_true和y_pred都是整数类标签。这是通过以下方式完成的:
y_pred = scipy.special.expit(y_pred)
y_true = y_true.astype(int)
Run Code Online (Sandbox Code Playgroud)
所以完整的工作代码是:
import seaborn as sns
from catboost import CatBoostClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from scipy.special import expit
df = sns.load_dataset('titanic')
X = df[['survived','pclass','age','sibsp','fare']]
y = X.pop('survived')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100)
class ProfitMetric:
@staticmethod
def get_profit(y_true, y_pred):
y_pred = expit(y_pred).astype(int)
y_true = y_true.astype(int)
#print("ACCURACY:",(y_pred==y_true).mean())
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
loss = 400*tp - 200*fn - 100*fp
return loss
def is_max_optimal(self):
return True # greater is better
def evaluate(self, approxes, target, weight):
assert len(approxes) == 1
assert len(target) == len(approxes[0])
y_true = np.array(target).astype(int)
approx = approxes[0]
score = self.get_profit(y_true, approx)
return score, 1
def get_final_error(self, error, weight):
return error
model = CatBoostClassifier(metric_period=50,
n_estimators=200,
eval_metric=ProfitMetric()
)
model.fit(X, y, eval_set=(X_test, y_test))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7654 次 |
| 最近记录: |