SKLearner Home | About | Contact | Examples

Scikit-Learn RandomizedSearchCV SelfTrainingClassifier

Hyperparameter tuning is essential for optimizing machine learning models. In this example, we’ll demonstrate how to use scikit-learn’s RandomizedSearchCV for hyperparameter tuning of a SelfTrainingClassifier, commonly used for semi-supervised learning tasks.

Random search is a method for evaluating different combinations of model hyperparameters. Unlike grid search, it samples a fixed number of hyperparameter combinations from a specified distribution, making it more efficient when searching over a large hyperparameter space.

SelfTrainingClassifier is a meta-estimator that allows a base classifier to learn from both labeled and unlabeled data. It iteratively predicts labels for the unlabeled data and adds them to the training set if the predictions are confident enough.

Key hyperparameters for SelfTrainingClassifier include base_estimator, which is the underlying classifier; threshold, which is the confidence level for adding pseudo-labels; and criterion, which determines the stopping criterion for self-training.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.semi_supervised import SelfTrainingClassifier
from sklearn.tree import DecisionTreeClassifier
from scipy.stats import uniform

# Generate synthetic semi-supervised dataset
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=42)

# Introduce missing labels for semi-supervised learning
import numpy as np
rng = np.random.RandomState(42)
random_unlabeled_points = rng.rand(len(y)) < 0.8
y[random_unlabeled_points] = -1  # -1 indicates unlabeled data

# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Define the base model
base_model = DecisionTreeClassifier(random_state=42)

# Define the self-training model
model = SelfTrainingClassifier(base_estimator=base_model)

# Define hyperparameter distribution
param_dist = {
    'base_estimator__max_depth': [3, 5, 10, None],
    'threshold': uniform(0.7, 0.3),
    'criterion': ['k_best', 'threshold']
}

# Perform random search
random_search = RandomizedSearchCV(estimator=model,
                                   param_distributions=param_dist,
                                   n_iter=100,
                                   cv=5,
                                   scoring='accuracy',
                                   random_state=42)
random_search.fit(X_train, y_train)

# Report best score and parameters
print(f"Best score: {random_search.best_score_:.3f}")
print(f"Best parameters: {random_search.best_params_}")

# Evaluate on test set
best_model = random_search.best_estimator_
accuracy = best_model.score(X_test, y_test)
print(f"Test set accuracy: {accuracy:.3f}")

Running the example gives an output like:

Best score: 0.177
Best parameters: {'base_estimator__max_depth': 10, 'criterion': 'k_best', 'threshold': 0.9598528437324805}
Test set accuracy: 0.150

The steps are as follows:

  1. Generate a synthetic semi-supervised classification dataset using scikit-learn’s make_classification function.
  2. Introduce missing labels in the dataset to simulate unlabeled data for semi-supervised learning.
  3. Split the dataset into train and test sets using train_test_split.
  4. Define the base model, in this case, a DecisionTreeClassifier.
  5. Create the SelfTrainingClassifier with the base model and initial parameters.
  6. Define the hyperparameter distribution for base_estimator__max_depth, threshold, and criterion.
  7. Perform random search using RandomizedSearchCV, specifying the SelfTrainingClassifier, hyperparameter distribution, 100 iterations, 5-fold cross-validation, and accuracy scoring metric.
  8. Report the best cross-validation score and best set of hyperparameters found by random search.
  9. Evaluate the best model on the hold-out test set and report the accuracy.

By using RandomizedSearchCV, we can efficiently explore different hyperparameter settings and find the combination that maximizes the model’s performance. This automated approach saves time and effort compared to manual hyperparameter tuning and helps ensure we select the best configuration for our SelfTrainingClassifier model.



See Also