Registry / ai-ml / optuna

optuna

JSON →
library4.9.0pypypi✓ verified 25d ago

Optuna is an automatic hyperparameter optimization framework for machine learning, featuring an imperative, define-by-run style user API that allows for dynamic construction of search spaces. It supports Python 3.9 or newer. The current version is 4.8.0, and it maintains an active development and release cadence, with major versions often introducing significant improvements and deprecating older features after a few releases.

pip install optuna
INSTALL
IMPORT
SIG · OPTUNA
O
optuna
ai-mlpythonv4.9.0
Install
6.7s avg
Import
765ms
Disk
127MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.9.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.768s · 125.6MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 6.7s · import 0.762s · 120MB
127MB installed
● package 127MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

optuna
import optuna
Trial
from optuna import Trial
from optuna.trial import Trial
While `from optuna.trial import Trial` works, `from optuna import Trial` is the more common and recommended import pattern for the core `Trial` object as of recent versions.

This quickstart defines an objective function that trains either an SVR or RandomForestRegressor, with hyperparameters sampled by Optuna's `Trial` object. It then creates a study to minimize the mean squared error over 100 trials, showcasing how Optuna dynamically builds search spaces and finds optimal hyperparameters.

import optuna import sklearn from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_squared_error def objective(trial: optuna.Trial) -> float: # Invoke suggest methods of a Trial object to generate hyperparameters. regressor_name = trial.suggest_categorical('regressor', ['SVR', 'RandomForest']) if regressor_name == 'SVR': svr_c = trial.suggest_float('svr_c', 1e-10, 1e10, log=True) regressor_obj = sklearn.svm.SVR(C=svr_c) else: rf_max_depth = trial.suggest_int('rf_max_depth', 2, 32) regressor_obj = RandomForestRegressor(max_depth=rf_max_depth, random_state=0) X, y = fetch_california_housing(return_X_y=True) X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0) regressor_obj.fit(X_train, y_train) y_pred = regressor_obj.predict(X_val) error = mean_squared_error(y_val, y_pred) return error if __name__ == '__main__': study = optuna.create_study(direction='minimize') # Create a new study study.optimize(objective, n_trials=100) # Invoke optimization print(f"Best trial value: {study.best_value:.4f}") print(f"Best params: {study.best_params}")
optuna --version
Debug
Known issues
breakingOptuna v4.x removed features deprecated in v2.x. This includes the `optuna.multi_objective` submodule and `MOTPESampler`. If migrating from older versions, consult the v4 migration guide for a complete list of removed APIs.
fix
Review the Optuna v4 Migration Guide. For multi-objective optimization, the functionality was integrated into the single-objective API in v2.4.0, so adapt your code to use the unified API.
affects: >=4.0.0
breakingThe paths for `IntersectionSearchSpace` and `intersection_search_space` moved from `optuna.samplers` to `optuna.search_space`. Additionally, `intersection_search_space` now takes `trials` instead of `study` and the `ordered_dict` argument was removed as dictionaries are now ordered by default.
fix
Update import paths and argument signatures for `IntersectionSearchSpace` and `intersection_search_space` to reflect their new locations and API changes.
affects: >=4.0.0
deprecatedPython 3.8 support was dropped in Optuna v4.x.
fix
Upgrade your Python environment to Python 3.9 or newer.
affects: >=4.0.0
gotchaFor some samplers, such as `TPESampler`, certain arguments have been made keyword-only, and the behavior of `consider_prior` argument might have changed or been simplified.
fix
Ensure all arguments for samplers are passed as keyword arguments and review sampler-specific documentation for changes in argument behavior or deprecations.
affects: >=4.4.0
gotchaSophisticated schedulers (e.g., `AsyncHyperBandScheduler`) may not work correctly with multi-objective optimization, as they typically expect a scalar score to compare fitness among trials.
fix
When performing multi-objective optimization, be mindful of scheduler compatibility. Consider using samplers and pruners specifically designed or enhanced for multi-objective tasks (e.g., `GPSampler` with multi-objective support from v4.4).
affects: All versions
gotchaA `ModuleNotFoundError` for 'sklearn' indicates that the `scikit-learn` package is not installed in the test environment. Scripts that use Optuna in conjunction with `sklearn` or other external libraries require those dependencies to be explicitly installed.
fix
Ensure all necessary external dependencies are installed in your environment. For `sklearn`, install it using `pip install scikit-learn`.
affects: All versions
gotchaThe test script or a specific feature of Optuna being tested requires the `scikit-learn` package, which is an optional dependency for certain Optuna functionalities (e.g., for some `TPESampler` configurations or `optuna.integration.skopt`). This leads to a `ModuleNotFoundError` if `scikit-learn` is not installed.
fix
Ensure the `scikit-learn` package is installed in your Python environment if you are using Optuna features that rely on it (e.g., `pip install scikit-learn`).
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'optuna'
The Optuna library is not installed in the Python environment being used, or the environment where it was installed is not active. This can also happen due to an incorrect Python interpreter selected in an IDE.
fix
Ensure Optuna is installed in your active Python environment using `pip install optuna`. If using a virtual environment or IDE, verify that the correct environment/interpreter is selected.
AttributeError: module 'optuna.samplers' has no attribute 'GridSampler'
This error typically occurs when trying to use a sampler (like `GridSampler` or `NSGAIISampler`) that was introduced in a newer version of Optuna than what is currently installed, or a sampler that has been moved/renamed. `GridSampler` was added in a later version, and older Optuna versions (e.g., 0.10.0) do not have it.
fix
Upgrade your Optuna library to a recent version using `pip install --upgrade optuna`. If the sampler was deprecated or renamed, refer to the official Optuna documentation for the correct class name or usage (e.g., `GridSampler` is available in newer versions).
AttributeError: 'Trial' object has no attribute 'suggest_loguniform'
The `suggest_loguniform` method was deprecated in Optuna. The functionality is now integrated into `trial.suggest_float` by using the `log=True` argument.
fix
Replace `trial.suggest_loguniform(name, low, high)` with `trial.suggest_float(name, low, high, log=True)`. Similarly, `suggest_uniform` is replaced by `suggest_float` without `log=True`.
sqlite3.OperationalError: database is locked
This error occurs when multiple Optuna processes or threads attempt to access and modify the same SQLite database file concurrently. SQLite is not designed for highly concurrent write operations, making it unsuitable for parallel optimization with multiple workers directly on the same file.
fix
For parallel optimization, use a more robust RDB backend like PostgreSQL or MySQL instead of SQLite. If you must use a file-based storage, consider `JournalFileStorage` for multi-processing or ensure sequential access to the SQLite database. You can also try increasing the database connection timeout with `engine_kwargs={'connect_args': {'timeout': 10}}` in `optuna.storages.RDBStorage`.
RuntimeError: This attribute is not available during multi-objective optimization.
This error occurs when attempting to access single-objective specific attributes (like `study.best_value` or `study.direction`) on a `Study` object that was created for multi-objective optimization. Multi-objective studies do not have a single 'best value' or 'direction'.
fix
For multi-objective studies, use the plural attributes such as `study.best_trials` to retrieve the Pareto front, and `study.directions` to get all objective directions. If you intend a single-objective study, ensure it is configured with a single objective direction when created (e.g., `optuna.create_study(direction='maximize')`).
Upgrade
Version history
4.9.0latest on PyPI · released Jun 1, 2026
Audit
Dependencies
scikit-learnoptionalCommonly used for examples and integration with ML models.
optuna-dashboardoptionalProvides a real-time web dashboard for visualizing optimization history and hyperparameter importance.
Agent activity
56 hits · last 30 days
node
52
OpenAI (training)
1
Resources
optuna — pip install optuna · libregistry