python - 自定义损失函数 sklearn

标签 python scikit-learn

我想在数据科学项目中做预测,通过非对称函数计算误差。

是否可以调整随机森林或梯度提升(sklearn)的损失函数?

我读到需要修改 .pyx 文件,但我在我的 sklearn 文件夹中找不到任何文件(我在 ubuntu 14.04 LTS 上)。

你有什么建议吗?

最佳答案

是的,可以调整。例如:

class ExponentialPairwiseLoss(object):
    def __init__(self, groups):
        self.groups = groups

    def __call__(self, preds, dtrain):
        labels = dtrain.get_label().astype(np.int)
        rk = len(np.bincount(labels))
        plus_exp = np.exp(preds)
        minus_exp = np.exp(-preds)
        grad = np.zeros(preds.shape)
        hess = np.zeros(preds.shape)
        pos = 0
        for size in self.groups:
            sum_plus_exp = np.zeros((rk,))
            sum_minus_exp = np.zeros((rk,))
            for i in range(pos, pos + size, 1):
                sum_plus_exp[labels[i]] += plus_exp[i]
                sum_minus_exp[labels[i]] += minus_exp[i]
            for i in range(pos, pos + size, 1):
                grad[i] = -minus_exp[i] * np.sum(sum_plus_exp[:labels[i]]) +\
                          plus_exp[i] * np.sum(sum_minus_exp[labels[i] + 1:])
                hess[i] = minus_exp[i] * np.sum(sum_plus_exp[:labels[i]]) +\
                          plus_exp[i] * np.sum(sum_minus_exp[labels[i] + 1:])
            pos += size
        return grad, hess

关于python - 自定义损失函数 sklearn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720878/

相关文章:

python - 减少matplotlib图中的左右边距

scikit-learn - 如何在sklearn中对连续属性进行离散化?

python - 值错误: Classification metrics can't handle a mix of multilabel-indicator and binary targets

python - 我们能否通过接受(或忽略)新功能使 ML 模型(pickle 文件)更加健壮?

Python 从异常中获取错误代码

python - Python 注释中行首的冒号

python - 尝试对用户输入数据进行标签编码时出现类型错误

python - PyErr_SetString 不会立即引发异常(Swig)?

python - Scikit-learn 平衡子采样

python - 如何使 sklearn.TfidfVectorizer 标记特殊短语?