sklearn sgdclassifier 的多输出预测?

multiple output prediction from sklearn sgd classifer?

我确实创建了一个与此类似的 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)

(免责声明:我的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]

首先,你的目标[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 array, shape (n_samples,)

Target values

可以说,您正在寻找的是 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

Multi target classification

This strategy consists of fitting one classifier per target. This is a simple strategy for extending classifiers that do not natively support multi-target classification