def test_estimate_competence_kuncheva_ex(): query = np.atleast_2d([1, 1]) a_posteriori_test = APosteriori([create_base_classifier(return_value=1)], k=k_ex_kuncheva) a_posteriori_test.n_classifiers_ = 1 a_posteriori_test.DSEL_processed_ = dsel_processed_kuncheva a_posteriori_test.dsel_scores_ = dsel_scores_ex_kuncheva a_posteriori_test.DSEL_target_ = y_dsel_ex_kuncheva_dependent a_posteriori_test.n_classes_ = n_classes_ex_kuncheva neighbors = neighbors_ex_kuncheva.reshape(1, -1) distances = distances_ex_kuncheva.reshape(1, -1) predictions = [] for clf in a_posteriori_test.pool_classifiers: predictions.append(clf.predict(query)[0]) competences = a_posteriori_test.estimate_competence( query, neighbors, distances, predictions=np.array(predictions)) assert np.isclose(competences, 0.95, atol=0.01)
def test_estimate_competence_diff_target(index, example_all_ones): _, _, neighbors, distances, dsel_processed, _ = example_all_ones query = np.atleast_2d([1, 1]) a_posteriori_test = APosteriori() a_posteriori_test.n_classifiers_ = 3 a_posteriori_test.DSEL_processed_ = dsel_processed a_posteriori_test.dsel_scores_ = np.ones((15, 3, 3)) a_posteriori_test.DSEL_target_ = np.ones(15, dtype=int) * 2 a_posteriori_test.n_classes_ = 2 neighbors = neighbors[index, :].reshape(1, -1) distances = distances[index, :].reshape(1, -1) expected = [0.0, 0.0, 0.0] predictions = np.array([0, 1, 0]) competences = a_posteriori_test.estimate_competence(query, neighbors, distances, predictions=np.array( predictions)) assert np.isclose(competences, expected).all()
def test_estimate_competence_kuncheva_ex_batch(example_kuncheva): # considering a batch composed of 10 samples query = np.ones((10, 2)) a_posteriori_test = APosteriori(k=example_kuncheva['k']) a_posteriori_test.fit(example_kuncheva['dsel_processed'], example_kuncheva['y_dependent']) a_posteriori_test.DSEL_processed_ = example_kuncheva['dsel_processed'] a_posteriori_test.dsel_scores_ = example_kuncheva['dsel_scores'] a_posteriori_test.n_classes_ = example_kuncheva['n_classes'] # repeating the same matrix in a new axis to simulate a batch input. neighbors = np.tile(example_kuncheva['neighbors'], (10, 1)) distances = np.tile(example_kuncheva['distances'], (10, 1)) predictions = np.ones((1, 10)) competences = a_posteriori_test.estimate_competence(query, neighbors, distances, predictions=np.array( predictions)) assert np.allclose(competences, 0.95, atol=0.01)
def test_estimate_competence_kuncheva_ex_batch(): # considering a batch composed of 10 samples query = np.ones((10, 2)) a_posteriori_test = APosteriori([create_base_classifier(return_value=1)], k=k_ex_kuncheva) a_posteriori_test.fit(dsel_processed_kuncheva, y_dsel_ex_kuncheva_dependent) a_posteriori_test.DSEL_processed_ = dsel_processed_kuncheva a_posteriori_test.dsel_scores_ = dsel_scores_ex_kuncheva a_posteriori_test.n_classes_ = n_classes_ex_kuncheva # repeating the same matrix in a new axis to simulate a batch input. neighbors = np.tile(neighbors_ex_kuncheva, (10, 1)) distances = np.tile(distances_ex_kuncheva, (10, 1)) predictions = [] for clf in a_posteriori_test.pool_classifiers: predictions.append(clf.predict(query)[0]) competences = a_posteriori_test.estimate_competence( query, neighbors, distances, predictions=np.array(predictions)) assert np.allclose(competences, 0.95, atol=0.01)
def test_estimate_competence_diff_target(index): query = np.atleast_2d([1, 1]) pool_classifiers = create_pool_classifiers() a_posteriori_test = APosteriori(pool_classifiers=pool_classifiers) a_posteriori_test.n_classifiers_ = len(pool_classifiers) a_posteriori_test.DSEL_processed_ = dsel_processed_ex1 a_posteriori_test.dsel_scores_ = np.ones((15, 3, 3)) a_posteriori_test.DSEL_target_ = np.ones(15, dtype=int) * 2 a_posteriori_test.n_classes_ = 2 neighbors = neighbors_ex1[index, :].reshape(1, -1) distances = distances_all_ones[index, :].reshape(1, -1) expected = [0.0, 0.0, 0.0] predictions = [] for clf in a_posteriori_test.pool_classifiers: predictions.append(clf.predict(query)[0]) competences = a_posteriori_test.estimate_competence(query, neighbors, distances, predictions=np.array( predictions)) assert np.isclose(competences, expected).all()
def test_estimate_competence_all_ones(index): query = np.atleast_2d([1, 1]) a_posteriori_test = APosteriori(create_pool_classifiers()) a_posteriori_test.fit(X_dsel_ex1, y_dsel_ex1) a_posteriori_test.DSEL_processed_ = dsel_processed_ex1 a_posteriori_test.dsel_scores_ = dsel_scores_all_ones neighbors = neighbors_ex1[index, :].reshape(1, -1) distances = distances_all_ones[index, :].reshape(1, -1) expected = [1.0, 1.0, 1.0] predictions = [] for clf in a_posteriori_test.pool_classifiers: predictions.append(clf.predict(query)[0]) competences = a_posteriori_test.estimate_competence( query, neighbors, distances, predictions=np.array(predictions)) assert np.isclose(competences, expected).all()
def test_estimate_competence_kuncheva_ex_batch(example_kuncheva): # considering a batch composed of 10 samples query = np.ones((10, 2)) classifier = MagicMock() classifier.predict.return_value = [1] classifier.predict_proba.return_value = None a_posteriori_test = APosteriori(pool_classifiers=classifier, k=example_kuncheva['k']) a_posteriori_test.n_classifiers_ = 1 a_posteriori_test.DSEL_processed_ = example_kuncheva['dsel_processed'] a_posteriori_test.DSEL_target_ = example_kuncheva['y_dependent'] a_posteriori_test.dsel_scores_ = example_kuncheva['dsel_scores'] a_posteriori_test.n_classes_ = example_kuncheva['n_classes'] # repeating the same matrix in a new axis to simulate a batch input. neighbors = example_kuncheva['neighbors'] distances = example_kuncheva['distances'] predictions = [1] competences = a_posteriori_test.estimate_competence( query, neighbors, distances, predictions=np.array(predictions)) assert np.allclose(competences, 0.95, atol=0.01)
def test_fit(): a_posteriori_test = APosteriori(create_pool_classifiers()) a_posteriori_test.fit(X_dsel_ex1, y_dsel_ex1) assert np.isclose(a_posteriori_test.dsel_scores, [0.5, 0.5, 1.0, 0.0, 0.33, 0.67]).all()
def _generate_local_pool(self, query): """ Local pool generation. This procedure populates the "pool_classifiers" based on the query sample's neighborhood. Thus, for each query sample, a different pool is created. In each iteration, the training samples near the query sample are singled out and a subpool is generated using the Self-Generating Hyperplanes (SGH) method. Then, the DCS technique selects the best classifier in the generated subpool and it is added to the local pool. In the following iteration, the neighborhood is increased and another SGH-generated subpool is obtained over the new neighborhood, and again the DCS technique singles out the best in it, which is then added to the local pool. This process is repeated until the pool reaches "n_classifiers". Parameters ---------- query : array of shape = [n_features] The test sample. Returns ------- self References ---------- M. A. Souza, G. D. Cavalcanti, R. M. Cruz, R. Sabourin, On the characterization of the oracle for dynamic classi er selection, in: International Joint Conference on Neural Networks, IEEE, 2017, pp. 332-339. """ n_samples, _ = self.DSEL_data.shape self.pool_classifiers = [] n_err = 0 max_err = 2 * self.n_classifiers curr_k = self.k # Classifier count n = 0 while n < self.n_classifiers and n_err < max_err: subpool = SGH() included_samples = np.zeros((n_samples), int) if self.knne: idx_neighb = np.array([], dtype=int) # Obtain neighbors of each class individually for j in np.arange(0, self.n_classes): # Obtain neighbors from the classes in the RoC if np.any(self.classes[j] == self.DSEL_target[ self.neighbors[0][np.arange(0, curr_k)]]): nc = np.where(self.classes[j] == self.DSEL_target[ self.neighbors[0]]) idx_nc = self.neighbors[0][nc] idx_nc = idx_nc[np.arange( 0, np.minimum(curr_k, len(idx_nc)))] idx_neighb = np.concatenate((idx_neighb, idx_nc), axis=0) else: idx_neighb = np.asarray(self.neighbors)[0][np.arange( 0, curr_k)] # Indicate participating instances in the training of the subpool included_samples[idx_neighb] = 1 curr_classes = np.unique(self.DSEL_target[idx_neighb]) # If there are +1 classes in the local region if len(curr_classes) > 1: # Obtain SGH pool subpool.fit(self.DSEL_data, self.DSEL_target, included_samples) # Adjust chosen DCS technique parameters if self.ds_tech == 'ola': ds = OLA(subpool, k=len(idx_neighb)) # change for self.k elif self.ds_tech == 'lca': ds = LCA(subpool, k=len(idx_neighb)) elif self.ds_tech == 'mcb': ds = MCB(subpool, k=len(idx_neighb)) elif self.ds_tech == 'mla': ds = MLA(subpool, k=len(idx_neighb)) elif self.ds_tech == 'a_priori': ds = APriori(subpool, k=len(idx_neighb)) elif self.ds_tech == 'a_posteriori': ds = APosteriori(subpool, k=len(idx_neighb)) # Fit ds technique ds.fit(self.DSEL_data, self.DSEL_target) neighb = np.in1d( self.neighbors, idx_neighb) # True/False vector of selected neighbors # Set distances and neighbors of the query sample (already calculated) ds.distances = np.asarray([self.distances[0][neighb] ]) # Neighborhood ds.neighbors = np.asarray([self.neighbors[0][neighb] ]) # Neighborhood ds.DFP_mask = np.ones(ds.n_classifiers) # Estimate competence comp = ds.estimate_competence(query, ds._predict_base(query)) # Select best classifier in subpool sel_c = ds.select(comp) # Add to local pool self.pool_classifiers.append(copy.deepcopy(subpool[sel_c[0]])) n += 1 # else: # # Exception: fewer than 2 classes in the neighborhood # print('OPS! Next!') # Increase neighborhood size curr_k += 2 n_err += 1 return self
def test_fit(): a_posteriori_test = APosteriori(create_pool_classifiers()) a_posteriori_test.fit(X_dsel_ex1, y_dsel_ex1) expected = np.array([[0.5, 0.5], [1.0, 0.0], [0.33, 0.67]]) expected = np.tile(expected, (15, 1, 1)) assert np.array_equal(a_posteriori_test.dsel_scores, expected)
X_train, y_train) model_svc = SVC(probability=True).fit(X_train, y_train) model_bayes = GaussianNB().fit(X_train, y_train) model_tree = DecisionTreeClassifier().fit(X_train, y_train) model_knn = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train) pool_classifiers = [ model_perceptron, model_linear_svm, model_svc, model_bayes, model_tree, model_knn ] # Initializing the DS techniques knop = KNOP(pool_classifiers) rrc = RRC(pool_classifiers) lca = LCA(pool_classifiers) mcb = MCB(pool_classifiers) aposteriori = APosteriori(pool_classifiers) # Fitting the techniques knop.fit(X_dsel, y_dsel) rrc.fit(X_dsel, y_dsel) lca.fit(X_dsel, y_dsel) mcb.fit(X_dsel, y_dsel) aposteriori.fit(X_dsel, y_dsel) # Calculate classification accuracy of each technique print('Evaluating DS techniques:') print('Classification accuracy KNOP: ', knop.score(X_test, y_test)) print('Classification accuracy RRC: ', rrc.score(X_test, y_test)) print('Classification accuracy LCA: ', lca.score(X_test, y_test)) print('Classification accuracy A posteriori: ', aposteriori.score(X_test, y_test))
def test_check_estimator(): check_estimator(APosteriori(selection_method='best'))
def test_not_predict_proba(create_X_y): X, y = create_X_y clf1 = Perceptron() clf1.fit(X, y) with pytest.raises(ValueError): APosteriori([clf1, clf1]).fit(X, y)
random_state=rng) # Split the data into training and DSEL for DS techniques X_train, X_dsel, y_train, y_dsel = train_test_split(X_train, y_train, test_size=0.5, random_state=rng) # Considering a pool composed of 10 base classifiers pool_classifiers = RandomForestClassifier(n_estimators=10, random_state=rng, max_depth=10) pool_classifiers.fit(X_train, y_train) # DS techniques without DFP apriori = APriori(pool_classifiers) aposteriori = APosteriori(pool_classifiers) ola = OLA(pool_classifiers) lca = LCA(pool_classifiers) desp = DESP(pool_classifiers) meta = METADES(pool_classifiers) apriori.fit(X_dsel, y_dsel) aposteriori.fit(X_dsel, y_dsel) ola.fit(X_dsel, y_dsel) lca.fit(X_dsel, y_dsel) desp.fit(X_dsel, y_dsel) meta.fit(X_dsel, y_dsel) print('Evaluating DS techniques:') print('Classification accuracy of OLA: ', ola.score(X_test, y_test)) print('Classification accuracy of LCA: ', lca.score(X_test, y_test))