gpt4 book ai didi

keras - 无法在多标签分类器上使用 Stratified-K-Fold

转载 作者:行者123 更新时间:2023-12-03 14:10:07 24 4
gpt4 key购买 nike

以下代码用于进行 KFold 验证,但我要训练模型,因为它抛出错误

ValueError: Error when checking target: expected dense_14 to have shape (7,) but got array with shape (1,)

我的目标变量有 7 个类。我正在使用 LabelEncoder将类编码为数字。

通过看到此错误,如果我将其更改为 MultiLabelBinarizer对类进行编码。我收到以下错误
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'multilabel-indicator' instead.

以下是KFold验证的代码
skf = StratifiedKFold(n_splits=10, shuffle=True)
scores = np.zeros(10)
idx = 0
for index, (train_indices, val_indices) in enumerate(skf.split(X, y)):
print("Training on fold " + str(index+1) + "/10...")
# Generate batches from indices
xtrain, xval = X[train_indices], X[val_indices]
ytrain, yval = y[train_indices], y[val_indices]
model = None
model = load_model() //defined above

scores[idx] = train_model(model, xtrain, ytrain, xval, yval)
idx+=1
print(scores)
print(scores.mean())

我不知道该怎么办。我想在我的模型上使用分层 K 折叠。请帮我。

最佳答案

MultiLabelBinarizer返回一个向量,该向量的长度为您的类数。

如果你看看如何StratifiedKFold splits你的数据集,你会看到它只接受一个一维的目标变量,而你试图传递一个维度为 [n_samples, n_classes] 的目标变量

分层拆分基本上保留了您的类(class)分布。如果你仔细想想,如果你有一个多标签分类问题,那就没有多大意义了。

如果您想保留目标变量中不同类别组合的分布,那么答案 here解释了您可以定义自己的分层拆分函数的两种方式。

更新:

逻辑是这样的:

假设你有 n类和您的目标变量是这些的组合 n类。您将拥有 (2^n) - 1组合(不包括全 0)。您现在可以创建一个新的目标变量,将每个组合视为一个新标签。

例如,如果 n=3 ,您将拥有 7独特的组合:

 1. [1, 0, 0]
2. [0, 1, 0]
3. [0, 0, 1]
4. [1, 1, 0]
5. [1, 0, 1]
6. [0, 1, 1]
7. [1, 1, 1]

将所有标签映射到这个新的目标变量。您现在可以简单地看待您的问题 多类分类,而不是 多标签分类。

现在可以直接使用 StartefiedKFold使用 y_new作为你的目标。拆分完成后,您可以将标签映射回去。

代码示例:
import numpy as np

np.random.seed(1)
y = np.random.randint(0, 2, (10, 7))
y = y[np.where(y.sum(axis=1) != 0)[0]]

输出:
array([[1, 1, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 1, 1],
[1, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 1, 0, 0]])

标签编码您的类向量:
from sklearn.preprocessing import LabelEncoder

def get_new_labels(y):
y_new = LabelEncoder().fit_transform([''.join(str(l)) for l in y])
return y_new

y_new = get_new_labels(y)

输出:
array([7, 6, 3, 3, 2, 5, 8, 0, 4, 1])

关于keras - 无法在多标签分类器上使用 Stratified-K-Fold,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890899/

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