主动学习数据集划分
此代码在20次循环里通过样本idx将数据集划分为三部分:测试集、未标注样本、已标注样本(每个类至少有一个已标注样本)
df = pd.read_csv("datasets/Automobile.csv", header=None) X = df.iloc[:, :-1].to_numpy() y = df.iloc[:, -1].to_numpy() TEST_SIZE = 0.3 UNLABELED_SIZE = 0.85 # 未标注池占非测试部分的比例,较大 for split_i in range(20): print(f" 第 {split_i} 次循环") seed = 42 + split_i * 100 rng = np.random.default_rng(seed) # 1) 分层抽测试集 sss = StratifiedShuffleSplit(n_splits=1, test_size=TEST_SIZE, random_state=seed) rest_idx, test_idx = next(sss.split(X, y)) y_rest = y[rest_idx] X_test , y_test = X[test_idx] , y[test_idx] # 2) 每个类别至少 1 个放入 labeled classes = np.unique(y_rest) one_per_class = [rng.choice(np.where(y_rest == c)[0], size=1)[0] for c in classes] # 3) 余下部分按比例抽 unlabeled,其余全归 labeled remaining = np.setdiff1d(np.arange(len(y_rest)), one_per_class) #生成剩余数组下标 n_unlabeled = max(1, int(len(remaining) * UNLABELED_SIZE)) unlabeled = rng.choice(remaining, size=n_unlabeled, replace=False) labeled = np.setdiff1d(np.arange(len(y_rest)), unlabeled)