gpt4 book ai didi

python - scikit-learn - 以概率为目标变量的多项逻辑回归

转载 作者:行者123 更新时间:2023-11-30 09:08:13 25 4
gpt4 key购买 nike

我正在使用 scikit-learn 在 Python 中实现多项逻辑回归模型。然而,问题是我想对目标变量的类别使用概率分布。举个例子,假设这是一个 3 类变量,如下所示:

    class_1 class_2 class_3
0 0.0 0.0 1.0
1 1.0 0.0 0.0
2 0.0 0.5 0.5
3 0.2 0.3 0.5
4 0.5 0.1 0.4

使每行的值之和等于 1。

我怎样才能拟合这样的模型?当我尝试时:

model = LogisticRegression(solver='saga', multi_class='multinomial')
model.fit(X, probabilities)

我收到一条错误消息:

ValueError: bad input shape (10000, 3)

我知道这与此方法需要向量而不是矩阵有关。但在这里我无法将概率矩阵压缩为向量,因为这些类不是唯一的。

最佳答案

在 scikit-learn 中不能使用非指标概率进行交叉熵损失; API 中未实现且不支持此功能。这是 scikit-learn 的限制。

对于逻辑回归,您可以根据实例的标签概率对实例进行上采样来近似它。例如,您可以将每个实例上采样 10 倍:如果对于训练实例,类 1 的概率为 0.2,类 2 的概率为 0.8,则生成 10 个训练实例:8 个类 2 和 2 个类 1。它不会像它应有的那样高效,但在有限的情况下将优化相同的目标函数。

你可以这样做:

from sklearn.utils import check_random_state
import numpy as np

def expand_dataset(X, y_proba, factor=10, random_state=None):
"""
Convert a dataset with float multiclass probabilities to a dataset
with indicator probabilities by duplicating X rows and sampling
true labels.
"""
rng = check_random_state(random_state)
n_classes = y_proba.shape[1]
classes = np.arange(n_classes, dtype=int)
for x, probs in zip(X, y_proba):
for label in rng.choice(classes, size=factor, p=probs):
yield x, label

在此处查看更完整的示例:https://github.com/TeamHG-Memex/eli5/blob/8cde96878f14c8f46e10627190abd9eb9e705ed4/eli5/lime/utils.py#L16

或者,您可以使用 TensorFlow 或 PyTorch 等库来实现逻辑回归;与 scikit-learn 不同,在这些框架中定义任何损失都很容易,并且交叉熵是开箱即用的。

关于python - scikit-learn - 以概率为目标变量的多项逻辑回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com