【问题标题】:multiple output prediction from sklearn sgd classifer?sklearn sgdclassifier的多输出预测?
【发布时间】:2019-03-08 18:09:55
【问题描述】:

我确实创建了一个与此类似的 scikit 模型。但现在我想提取两个输出。我不知道如何在训练时通过这个。我确实尝试过类似于 Keras。 [y,z] 作为列表。但它在 scikit 中不起作用。以前有人试过吗?

import numpy as np
from sklearn import linear_model
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
Y = np.array([1, 1, 2, 2])
Z = np.array([1, 1, 2, 2])
clf = linear_model.SGDClassifier(max_iter=1000)
clf.fit(X, [Y, Z])

输出:

ValueError: bad input shape (2, 4)

【问题讨论】:

    标签: python machine-learning scikit-learn classification gradient-descent


    【解决方案1】:

    首先,你的目标[Y, Z]不是你想的那样:

    [Y, Z]
    # [array([1, 1, 2, 2]), array([1, 1, 2, 2])]
    

    可以说,你想要的应该有四行,就像你的X,即

    W = np.array([[1, 1], [1, 1], [2, 2], [2, 2]])
    W
    # result:
    array([[1, 1],
           [1, 1],
           [2, 2],
           [2, 2]])
    

    但即使进行了此更改,您也会再次收到类似的错误:

    clf.fit(X, W)
    [...]
    ValueError: bad input shape (4, 2)
    

    因为,正如 SGDClassifier documentation 中明确提到的,您的因变量 y 应该只有一列:

    fit(X, y, coef_init=None, intercept_init=None, sample_weight=None)

    y : numpy 数组,形状 (n_samples,)

    目标值

    可以说,您正在寻找的是 scikit-learn 的 MultiOuputClassifier for multioutput classification

    from sklearn.multioutput import MultiOutputClassifier
    
    sgd = linear_model.SGDClassifier(max_iter=1000)
    multi_target_sgd = MultiOutputClassifier(sgd, n_jobs=-1)
    multi_target_sgd.fit(X, W) 
    

    fit 现在可以正常工作了,输出如下:

    MultiOutputClassifier(estimator=SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
           eta0=0.0, fit_intercept=True, l1_ratio=0.15,
           learning_rate='optimal', loss='hinge', max_iter=1000, n_iter=None,
           n_jobs=1, penalty='l2', power_t=0.5, random_state=None,
           shuffle=True, tol=None, verbose=0, warm_start=False),
               n_jobs=-1)
    

    请记住,主题分类器不会做任何比为每个目标输出拟合一个分类器更复杂的事情;再次来自docs

    多目标分类

    此策略包括为每个目标拟合一个分类器。这是一个 扩展本机不支持的分类器的简单策略 多目标分类

    【讨论】:

    • 我刚刚将自定义的 keras 模型转换为 scikit。感谢您提供详细信息。我明白了!
    【解决方案2】:

    (免责声明:我的 ML 有点生疏,但我有一种感觉,我知道你在找什么,这太长了,不能发表评论)

    您传递给clf.fit 的形状不正确。

    首先你要传递 X,这很好,它是一个包含数组的数组,每个内部数组都包含特征的值(对吗?)。

    现在,您传递的第二个参数是一个由 Y 和 Z 组成的数组。

    如果我们查看documentation for fit,我们可以看到 fit 函数需要一个 Y,它的格式如下:

    y : numpy array, shape (n_samples,)
    Target values
    

    这意味着它必须是包含这 n 个样本的单个数组。

    我不确定您要与 [Y, Z] 匹配什么,因为当您调用 clf.predict 时您期望的结果是什么,但我认为您没有正确形成目标数组.

    也许您应该将数组形成为 Y = Y + Z:

    YZ = [ [1,1], [1,1], [2,2], [2,2] ]
    

    通过使用这个 YZ 数组,当运行例如 clf.predict([-1, -1]) 时,输出如下:

    clf.predict([-1, -1])
    output: [1,1]
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2019-03-12
      • 2013-06-08
      • 2016-01-06
      • 1970-01-01
      • 2015-12-04
      • 2019-07-18
      • 2017-04-02
      • 2015-12-19
      相关资源
      最近更新 更多