【发布时间】:2021-03-22 22:22:15
【问题描述】:
我正在尝试在我的 ResNet-50 模型上实施分层 K 折交叉验证。
不幸的是,当我对标签进行一次热编码并尝试使用分层 k 折叠分割我的数据时,我得到了这个错误:
TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.
one-hot 编码器的实现方式如下:
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder()
enc.fit(Y)
Y = enc.transform(Y)
Y.toarray()
如果我不对标签进行一次性编码,则会因拟合模型而出现此错误:
ValueError: Shapes (None, 1) and (None, 4) are incompatible
这是实现 Stratified K-fold 的代码:
for train, test in skf.split(X, Y):
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dropout(0.7)(x)
predictions = Dense(num_classes, activation= 'softmax')(x)
model = Model(inputs = base_model.input, outputs = predictions)
adam = Adam(lr=0.0001)
model.compile(optimizer= adam, loss='categorical_crossentropy', metrics=['accuracy'])
# Training
history = model.fit(X[train], Y[train], epochs = 100, batch_size = 16)
其中 num_classes = 4。
所以我的问题是:
问:如何让 one-hot 编码标签与 skf.split() 一起使用?
【问题讨论】:
标签: machine-learning keras neural-network conv-neural-network one-hot-encoding