{"library":"optuna","code":"import optuna\nimport sklearn\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.metrics import mean_squared_error\n\ndef objective(trial: optuna.Trial) -> float:\n    # Invoke suggest methods of a Trial object to generate hyperparameters.\n    regressor_name = trial.suggest_categorical('regressor', ['SVR', 'RandomForest'])\n\n    if regressor_name == 'SVR':\n        svr_c = trial.suggest_float('svr_c', 1e-10, 1e10, log=True)\n        regressor_obj = sklearn.svm.SVR(C=svr_c)\n    else:\n        rf_max_depth = trial.suggest_int('rf_max_depth', 2, 32)\n        regressor_obj = RandomForestRegressor(max_depth=rf_max_depth, random_state=0)\n\n    X, y = fetch_california_housing(return_X_y=True)\n    X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0)\n\n    regressor_obj.fit(X_train, y_train)\n    y_pred = regressor_obj.predict(X_val)\n    error = mean_squared_error(y_val, y_pred)\n    return error\n\nif __name__ == '__main__':\n    study = optuna.create_study(direction='minimize')  # Create a new study\n    study.optimize(objective, n_trials=100)  # Invoke optimization\n\n    print(f\"Best trial value: {study.best_value:.4f}\")\n    print(f\"Best params: {study.best_params}\")\n","lang":"python","description":"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.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}