gpt4 book ai didi

python - RandomForestClassifier 为多标签类提供转置输出

转载 作者:行者123 更新时间:2023-12-01 04:05:59 26 4
gpt4 key购买 nike

由于某种原因,每当我运行 ensemble.RandomForestClassifier() 并使用 .predict_proba() 方法时,它都会返回一个形状为 [n_classes, n_samples] 而不是它应该的 [n_samples, n_classes] 形状 per the docs.

这是我的示例代码:

# generate some sample data

X = np.array([[4, 5, 6, 7, 8],
[0, 5, 6, 2, 3],
[1, 2, 6, 5, 8],
[6, 1, 1, 1, 3],
[2, 5, 3, 2, 0]])
»» X.shape
(5, 5)

y = [['blue', 'red'],
['red'],
['red', 'green'],
['blue', 'green'],
['orange']]

X_test = np.array([[4, 6, 1, 2, 8],
[0, 0, 1, 5, 1]])
»» X_test.shape
(2, 5)

# binarize text labels

mlb = preprocessing.MultiLabelBinarizer()
lb_y = mlb.fit_transform(y)

»» lb_y
[[1 0 0 1]
[0 0 0 1]
[0 1 0 1]
[1 1 0 0]
[0 0 1 0]]

»» lb_y.shape
(5, 4)

到目前为止,一切正常。但是当我这样做时:

rfc = ensemble.RandomForestClassifier(random_state=42)
rfc.fit(X, lb_y)
yhat_p = rfc.predict_proba(X_test)

»» yhat_p
[array([[ 0.5, 0.5],
[ 0.7, 0.3]]),
array([[ 0.4, 0.6],
[ 0.5, 0.5]]),
array([[ 0.7, 0.3],
[ 0.7, 0.3]]),
array([[ 0.7, 0.3],
[ 0.6, 0.4]])]

我的 yhat_p 大小是 [n_classes, n_samples] 而不是 [n_samples, n_classes]。有人可以告诉我为什么我的输出被转置吗?注意:.predict() 方法工作得很好。

最佳答案

通过对数据进行二值化,您已经改变了问题,因此您现在正在执行四个单独的分类任务。每个任务都有两个类,0 和 1,其中 1 代表“有这个标签”,0 代表“没有这个标签”。

文档中的格式有点奇怪,但它说:

array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1

由于您有四个输出,因此您将获得四个数组的列表。每个数组的形状都是 (2, 2),因为每个输出有两个样本(即 X_test 中的两行)和两个类(0 和 1)。文档中提到的 n_classes 是单个输出的类数,而不是您正在执行的所有输出分类的类总数。 (它返回一个列表而不是单个数组的原因是,单独的分类不需要具有相同数量的类。您可以执行多输出分类任务,其中一个输出有两个类,另一个输出有 100 个类。)

例如,列表中的第一个元素是

array([[ 0.5,  0.5],
[ 0.7, 0.3]]),

每一行都为您提供 X_test 的相应行属于第一个分类任务中每个类的概率,这本质上是“这个项目是不是蓝色的?”因此,第一行告诉您,第一个 X_test 行有 50% 的可能性不是蓝色,有 50% 的可能性是蓝色;第二行告诉您,第二个 X_test 行有 70% 的可能性不是蓝色,有 30% 的可能性是蓝色。

关于python - RandomForestClassifier 为多标签类提供转置输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588696/

26 4 0