Zero Labs
Industry News / AI

Beyond Hyperparameters: Using Optuna for Bayesian Feature Selection

Source · Towards AI By Konrad "Stellars" Jelen

From the publisher’s feed, collected in the ZeroLabs newsroom.

How we repurposed a hyperparameter tuning framework to solve the feature selection problem in a real predictive maintenance projectWhat is Optuna?If you’ve worked with machine learning, you know that finding the right hyperparameters is tedious. Learning rate, number of layers, regularization strength — the combinations are endless. Optuna is an open-source optimization framework that automates this search using intelligent sampling strategies instead of brute force.At its core, Optuna uses a Tree-structured Parzen Estimator (TPE) — a Bayesian optimization algorithm. Instead of trying every combination (grid search) or throwing darts blindly (random search), TPE builds a probabilistic model of which parameter values tend to produce good results. Each trial informs the next, so the search gets smarter over time.import optunadef objective(trial): lr = trial.suggest_float("learning_rate", 1e-5, 1e-1, log=True) n_layers = trial.suggest_int("n_layers", 1, 5) # train model, return score return scorestudy = optuna.create_study(direction="maximize")study.optimize(objective, n_trials=100)That’s the standard use case. Define an objective, suggest parameters, optimize. Simple and effective.But what if the thing you need to optimize isn’t a number?The Feature Selection ProblemOur team at a Swedish dairy equipment manufacturer builds anomaly detection models for automated milking stations — robotic milking machines used on dairy farms worldwide. These systems generate time-series sensor data: vacuum pressure, milk yield, hydraulic oil pressure, cup positions, water temperature, and dozens more.From raw sensor readings, our feature engineering pipeline produces derivative features — rolling averages, FFT frequency components, spread metrics, lag indicators, duration estimates. The feature engineering effort alone was substantial — transforming a handful of raw sensor channels into a rich representation of machine behavior. By the time we’re done, a single milking session is described by roughly 240 features.Not all of them matter. Some are noisy. Some are redundant. Some actively hurt model performance by introducing spurious correlations. We needed to find the right subset.The classic approaches each have problems at this scale:· Manual selection — We tried this first. Domain experts picked features they thought mattered. It worked, but it was slow, biased toward known signals, and couldn’t explore unexpected combinations· Correlation-based filtering — Removes redundant features but can’t tell you which ones a model actually needs· Recursive Feature Elimination (RFE) — Computationally expensive with 240 features and doesn’t explore the combinatorial space well· L1 regularization — Helps with linear models but our pipeline uses autoencoders and XGBoost· Random search — We actually tried randomly sampling feature subsets. The search space is 2²⁴⁰ combinations. Random sampling barely scratches the surfaceWe needed something that could search intelligently across both the number of features to use and which specific features to include. Something that learns from previous attempts.That’s when we looked at Optuna differently.The Idea: Features as Continuous ParametersThe key insight is surprisingly simple. Instead of treating feature selection as a discrete combinatorial problem (include feature X: yes/no), we can reformulate it as a continuous optimization problem.Here’s how it works:1. Assign each feature a rank — a continuous float value between 0.0 and 1.02. Decide how many features to keep — an integer parameter k3. Select the top-k features by their rank values4. Train and evaluate the model with only those features5. Let Optuna’s TPE sampler learn which rank configurations produce better scoresThe rank values aren’t meaningful on their own. What matters is their relative ordering. Optuna’s Bayesian optimizer will gradually learn that certain features consistently need high ranks (they’re important) and others should rank low (they’re noise)def optuna_suggest_features(trial, all_features, k): """Suggest a subset of features using continuous rank values.""" ranks = [ trial.suggest_float(f"feature_rank_{i}_{name}", 0.0, 1.0) for i, name in enumerate(all_features) ] sorted_indices = sorted( range(len(all_features)), key=lambda i: ranks[i], reverse=True ) return [all_features[i] for i in sorted_indices[:k]]This is the core trick. We’ve converted a discrete selection problem into 240 continuous parameters plus one integer parameter. And Optuna’s TPE sampler is specifically designed to handle mixed parameter spaces efficiently.Encoding and Decoding Feature NamesThere’s a practical problem that’s easy to overlook. Real-world feature names are messy. Ours looked like S_HydraulicOilPressure_FFT, SYN_LBL_STATE_Milking_DUR, or S_VacuumCup_Spread - full of special characters, mixed case, and varying lengths. Optuna stores every suggested parameter by name in its trial registry, and these names need to be safe, unique, and - crucially - decodable back to the original feature after optimization finishes.Our solution uses a structured naming convention with three components: a namespace prefix, the feature’s positional index, and a slugified version of the feature name.from slugify import slugifyPREFIX_FEATURE_RANK = "feature_rank"# Encoding: during trial suggestionranks = [ trial.suggest_float( f"{PREFIX_FEATURE_RANK}_{namespace}_{i}_{slugify(f, separator='_', lowercase=False)}", 0.0, 1.0 ) for i, f in enumerate(all_features)]A feature like S_HydraulicOilPressure_FFT becomes the Optuna parameter feature_rank_default_7_S-HydraulicOilPressure-FFT. The slugify call strips anything that could break parameter lookups while keeping the name human-readable. The positional index _7_ guarantees stable ordering - even if two features slugify to similar strings, their indices keep them distinct.The namespace prefix (default in this example) is important when you're running multiple feature groups through the same study. You might want to optimize sensor features and FFT features separately, or combine them. Namespacing keeps the parameter spaces cleanly separated.Decoding after optimization works by filtering trial parameters by prefix and reconstructing the rank ordering:def optuna_decode_features(trial, all_features, top_k_param_name="top_k", namespace="default"): top_k = trial.params[top_k_param_name] feature_rank_name = f"{PREFIX_FEATURE_RANK}_{namespace}" # Collect all rank values in feature order ranks = [ value for key, value in trial.params.items() if feature_rank_name in key ] # Sort by rank, take top-k sorted_indices = sorted(range(len(all_features)), key=lambda i: ranks[i], reverse=True) return [all_features[i] for i in sorted_indices[:top_k]]This encode/decode pattern means you can pass the best trial around, serialize it, or load it from an Optuna study database later, and always recover the exact feature set. Without it, you’d be stuck mapping anonymous float parameters back to feature names manually — a headache at 240 features.ImplementationThe Objective FunctionIn our production setup, the objective function trains an anomaly detection model and returns its cross-validated F1 score. But the structure is the same as any Optuna study:class FeaturesTuner: def __init__(self, features, min_features_count=1): self.features = list(features) self.min_features_count = min_features_count self.study = None def objective(self, trial): # Step 1: How many features? k = trial.suggest_int("k", self.min_features_count, len(self.features)) # Step 2: Which features? (using dynamic ranking) selected = optuna_suggest_features( trial=trial, all_features=self.features, k=k ) # Step 3: Train model with selected features, return score score = train_and_evaluate(selected) return scoreRunning the StudyWe used the TPE sampler with a fixed seed for reproducibility:from optuna.samplers import TPESamplersampler = TPESampler(seed=42)study = optuna.create_study( study_name="feature_selection_optimizer", direction="maximize", sampler=sampler,)study.optimize( tuner.objective, n_trials=500, n_jobs=1, # sequential for reproducibility show_progress_bar=True, callbacks=[early_stopping_callback],)A few practical notes:Sequential execution (n_jobs=1) gave us more consistent convergence than parallel trials. The Bayesian sampler benefits from seeing each result before suggesting the next trialEarly stopping saved significant compute time. We halted the study when the score plateaued for 50 consecutive trials500 trials was our budget. With 240 features, the search space is enormous, but TPE’s intelligent sampling made this sufficient to find strong configurationsDecoding ResultsAfter optimization, extracting the best feature set is straightforward:best_trial = study.best_trialbest_k = best_trial.params["k"]# Retrieve rank values and select top-kranks = []for key, value in best_trial.params.items(): if key.startswith("feature_rank_"): ranks.append(value)sorted_indices = sorted( range(len(all_features)), key=lambda i: ranks[i], reverse=True)best_features = [all_features[i] for i in sorted_indices[:best_k]]We also built a visualization function that plots the rank distribution, highlighting selected features in red:def visualize_feature_ranks(trial, top_k): """Bar chart of feature ranks, top-k highlighted in red.""" rank_items = [ (k, v) for k, v in trial.params.items() if k.startswith("feature_rank_") ] rank_items.sort(key=lambda x: x[1], reverse=True) labels = [item[0].split("_", 4)[4] for item in rank_items] values = [item[1] for item in rank_items] colors = ["red" if i for i in range(len(values))] plt.bar(labels, values, color=colors) plt.title(f"Feature Ranks (Top {top_k} Highlighted)") plt.xticks(rotation=45, ha="right") plt.show()This visualization is genuinely useful. You can see a clear separation between features the optimizer considers important (high ranks) and those it consistently pushes down. It gave us confidence that the results weren’t random.ResultsWe ran this approach across a series of experiments on our anomaly detection classification task. Each experiment used identical model architecture, training procedure, and evaluation protocol — the only variable was the feature set.Baseline (manual feature selection): 78% F1 score. This was our starting point, using features hand-picked by domain experts — vacuum sensors, milk yield, hydraulic pressure, and a handful of derived metrics.After Optuna feature selection: Over 84% F1 score. The optimizer consistently found feature combinations that outperformed manual selection across subsequent experiment batches.That’s a 6+ percentage point improvement on F1, which in a production predictive maintenance system translates directly to fewer missed breakdowns and fewer false alarms.What surprised us most was what the optimizer found:Some features we considered essential (based on domain knowledge) were dropped entirely. The model performed better without themSeveral FFT-derived frequency features that we’d been unsure about turned out to be criticalThe optimal number of features (k) was dramatically smaller than our original 240. The optimizer typically converged on 20-30 features - barely a tenth of the available pool. This was the sweet spot where the model had enough signal without drowning in noiseFeature combinations mattered. Some features were individually weak but powerful when paired with specific others — something manual selection almost never discoversLimitationsThis approach is not perfect. It’s important to be honest about where it falls short:Computational cost — Each trial requires a full model training and evaluation cycle. With 500 trials, that’s 500 model trainings. For lightweight models this is fine. For deep learning models, it gets expensiveSearch space scaling — 240 continuous parameters is a lot even for TPE. The sampler needs many trials before its probability model becomes reliable. With 1000+ features, you’d likely need thousands of trialsNo feature interaction modeling — Optuna treats each feature rank independently. It can discover good combinations through trial and error, but it doesn’t explicitly model feature interactionsReproducibility caveats — While we seed the sampler, the optimization landscape is complex. Different seeds can produce different (though similarly performing) feature subsetsNot a replacement for domain knowledge — The optimizer might select features that happen to correlate with the target in your training data but have no causal relationship. Domain review of the selected features is still essentialWhen to Use This ApproachThis technique works best when:You have a moderate number of features (50–500 range)Training a single model is relatively fast (minutes, not hours)You’ve exhausted simpler approaches like correlation filteringYou suspect the feature space contains hidden redundancyYou need a reproducible, automated selection processIt’s particularly well-suited for iterative projects where you’re continuously adding new features and need to re-evaluate which ones to keep.Practical TipsA few things we learned the hard way:Start with a proof of concept — Before running against your real model, test the optimization loop with a mocked scoring function. We built a simple mock that gave known-good features a score of 1.0 each. This validated that the TPE sampler could actually converge on the correct features before we spent GPU hours on real trainingUse namespaced parameters — If you’re optimizing features from multiple sources (raw sensors, FFT features, lag features), use prefixed parameter names. It makes decoding and analysis much cleanerLog everything — Save the full Optuna study object. You can analyze trial history, plot convergence curves, and extract feature importance patterns after the factRun multiple seeds — Features that appear in the top-k across different random seeds are robust selections. Features that only appear with one seed might be noiseSet a minimum feature count — Don’t let k go below a reasonable floor. An optimizer that converges on 2 features might be overfitting to the evaluation metricConclusionOptuna is marketed as a hyperparameter optimization framework, and it’s excellent at that job. But the underlying Bayesian optimization engine is more general than most people realize. By encoding feature selection as continuous rank parameters, you can leverage TPE’s intelligent search to navigate enormous feature spaces.For our predictive maintenance project, this approach took us from 78% to over 84% F1 — narrowing 240 engineered features down to a tight set of 20–30 that the model actually needed. The code is straightforward, the concept is simple, and it plugs into any existing Optuna workflow.If you’re drowning in features and manual selection isn’t cutting it, give this a try. The optimizer might surprise you with what it finds.The author is a lead data scientist with years of experience in manufacturing business and intelligent automation systems.Beyond Hyperparameters: Using Optuna for Bayesian Feature Selection was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.