python - sklearn 中的多类概率标签数据和同类型预测使用什么?

标签 python machine-learning scikit-learn

我有一个标有 4 个不同类别的概率值的数据,我也想以这种方式进行预测。然而,我找不到任何处理此类数据并预测每个类的概率值而不是二进制顺序的算法。遇到这样的问题我可以用什么?

最佳答案

scikit-learn 分类器不支持开箱即用的概率分布训练。解决方法是使用概率分布作为 sample_weight,将样本 K 次提供给 K 类的训练算法。并非所有分类器都支持这一点,但 SGDClassifier 确实并且将会使用正确的设置拟合逻辑回归模型。

为了举例,让我们制作一个随机训练集。

>>> X = np.random.randn(10, 6)
>>> p_pos = np.random.random_sample(10)
>>> p_pos
array([ 0.19751302,  0.01538067,  0.87723187,  0.63745719,  0.38188726,
        0.62435933,  0.3706495 ,  0.12011895,  0.61787941,  0.82476533])

现在将其输入到使用 SGD 训练的逻辑回归模型中,两次

>>> lr = SGDClassifier(loss="log")
>>> y = p_pos > .5
>>> lr.fit(np.vstack([X, X]), np.hstack([np.ones(10), np.zeros(10)]),
...        sample_weight=np.hstack([p_pos, 1 - p_pos]))
SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0,
       fit_intercept=True, l1_ratio=0.15, learning_rate='optimal',
       loss='log', n_iter=5, n_jobs=1, penalty='l2', power_t=0.5,
       random_state=None, shuffle=False, verbose=0, warm_start=False)

前面的示例是针对二进制 LR 的。多类 LR 稍微复杂一些。假设您有一个由 n_samples 个概率分布组成的矩阵 P,每个矩阵都有一个行向量:

>>> P = np.abs(np.random.randn(10, 4))
>>> P /= P.sum(axis=1).reshape(-1, 1)  # normalize
>>> P
array([[ 0.22411769,  0.06275884,  0.25062665,  0.46249682],
       [ 0.20659542,  0.06153031,  0.03973449,  0.69213978],
       [ 0.20214651,  0.084988  ,  0.12751119,  0.5853543 ],
       [ 0.35839192,  0.30211805,  0.01093208,  0.32855796],
       [ 0.34267131,  0.07151225,  0.09413323,  0.4916832 ],
       [ 0.26670351,  0.30988833,  0.22118608,  0.20222208],
       [ 0.00694437,  0.68845955,  0.18413326,  0.12046281],
       [ 0.34344352,  0.27397581,  0.34626692,  0.03631376],
       [ 0.29315434,  0.25683875,  0.14935136,  0.30065555],
       [ 0.19147437,  0.22572122,  0.57924412,  0.00356029]])

现在我们有四个类,因此我们需要将训练集提供给估计器四次。

>>> n_classes = P.shape[1]
>>> X4 = np.vstack([X for i in xrange(n_classes)])
>>> y = np.arange(n_classes).repeat(10)
>>> sample_weight = P.T.ravel()
>>> lr.fit(X4, y, sample_weight=sample_weight)
SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0,
       fit_intercept=True, l1_ratio=0.15, learning_rate='optimal',
       loss='log', n_iter=5, n_jobs=1, penalty='l2', power_t=0.5,
       random_state=None, shuffle=False, verbose=0, warm_start=False)

关于python - sklearn 中的多类概率标签数据和同类型预测使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170191/

相关文章:

python - 无法更改一列中的分类数据(pandas、机器学习)

python - 使用Vicuna + langchain + llama_index 创建自托管LLM模型

machine-learning - 受限玻尔兹曼机中 "extracting 8x8 patches"背后的原因是什么?

python - Sklearn神经网络问题

python - 如何在不过度采样的情况下平衡数据集

Python,奇怪的内存消耗行为

python - 减少多列中的多个ID

python - 如何让one-hot数据与非one-hot数据兼容?

python - 如何从与 scikit-learn 中的 predict_proba 一起使用的 cross_val_predict 获取类标签

python - 如何在 Keras 中的预训练 InceptionResNetV2 模型的不同层中找到激活的形状 - Tensorflow 2.0