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 LabelSpreading
model, 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.
LabelSpreading
is a graph-based semi-supervised learning algorithm that propagates labels through the data graph based on similarity. The model leverages both labeled and unlabeled data to improve classification performance.
Key hyperparameters for LabelSpreading
include the kernel
, which determines the affinity matrix and can be ‘knn’ or ‘rbf’; gamma
, which is used when the rbf
kernel is selected and defines the spread of the RBF kernel; and n_neighbors
, which is used when the knn
kernel is selected and specifies the number of neighbors to use.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.semi_supervised import LabelSpreading
from scipy.stats import uniform
# Generate synthetic dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=10, n_redundant=10, random_state=42)
y[::100] = -1 # Unlabel 10% of the 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 model
model = LabelSpreading()
# Define hyperparameter distribution
param_dist = {
'kernel': ['knn', 'rbf'],
'gamma': uniform(loc=0, scale=1),
'n_neighbors': range(3, 5)
}
# Perform random search
random_search = RandomizedSearchCV(estimator=model,
param_distributions=param_dist,
n_iter=50,
cv=3,
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.895
Best parameters: {'gamma': 0.3745401188473625, 'kernel': 'knn', 'n_neighbors': 3}
Test set accuracy: 0.945
The steps are as follows:
- Generate a synthetic dataset with a mix of labeled and unlabeled data using
make_classification
. - Split the dataset into train and test sets using
train_test_split
. - Define the
LabelSpreading
model. - Specify the hyperparameter distribution for
kernel
,gamma
, andn_neighbors
. - Use
RandomizedSearchCV
to perform random search, specifying theLabelSpreading
model, hyperparameter distribution, 100 iterations, 5-fold cross-validation, and accuracy scoring metric. - Report the best cross-validation score and the optimal set of hyperparameters found by random search.
- Evaluate the best model on the hold-out test set and report the test set 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 LabelSpreading
model.