自定义 ImageDataGenerator 以在多标签上进行分层抽样

Customize ImageDataGenerator for stratified sampling on Multi-Labels

我正在处理 multi-label classification 我的 large-scale 数据高度 imbalanced 的问题。因此,我需要应用 stratified sampling,直觉是我的 ImageDataGenerator 按比例从 every batch 中的 each class 采样数据。任何 suggestion/solution 将不胜感激。

确实是个好问题。

据我所知,ImageDataGenerator() 中没有内置多标签分层。

我会建议两种可能的方法:

  1. 您可以将 class 子 Sequence() class 子Sequence() class 以便能够准确控制您在网络中的每一步提供的内容。您可以覆盖 __getitem__() 方法,并确保数据在每批中按比例采样。

  2. 您可以使用外部库在将数据提供给网络之前对数据进行预处理。通过这种方式,您可以预处理数据并使用 tf.data.Dataset() 管道将数据提供给您的网络。

(2) 的一个例子是这个:

from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import numpy as np

X = np.array([[1,2], [3,4], [1,2], [3,4], [1,2], [3,4], [1,2], [3,4]])
y = np.array([[0,0], [0,0], [0,1], [0,1], [1,1], [1,1], [1,0], [1,0]])

mskf = MultilabelStratifiedKFold(n_splits=2, shuffle=True, random_state=0)

for train_index, test_index in mskf.split(X, y):
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = X[train_index], X[test_index]
   y_train, y_test = y[train_index], y[test_index]