Hyperparameter Tuning praktis menggunakan GridSearchCV dan RandomizedSearchCV
Mengapa Hyperparameter Tuning Penting
Setiap algoritma machine learning memiliki konfigurasi yang dapat disesuaikan. Parameter-parameter ini, yang disebut hyperparameter, menentukan bagaimana model belajar dari data. Pilihan hyperparameter yang suboptimal menghasilkan model dengan performa rendah, bahkan ketika data berkualitas tinggi.
Kita perlu mencari kombinasi hyperparameter terbaik secara sistematis. Manual tuning memakan waktu dan tidak efisien. GridSearchCV dan RandomizedSearchCV memberikan solusi otomatis untuk eksplorasi ruang hyperparameter.
Memahami GridSearchCV
GridSearchCV melakukan exhaustive search melintasi kombinasi hyperparameter yang telah didefinisikan. Metode ini mencoba setiap kemungkinan kombinasi dari parameter grid yang kita tentukan.
!pip install scikit-learn pandas
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
# Load dataset
iris = load_iris()
X, y = iris.data, iris.target
# Definisikan model
rf = RandomForestClassifier(random_state=42)
# Setup parameter grid
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [3, 5, 7, None],
'min_samples_split': [2, 5, 10]
}
# Inisialisasi GridSearchCV
grid_search = GridSearchCV(
estimator=rf,
param_grid=param_grid,
cv=5,
scoring='accuracy',
n_jobs=-1,
verbose=1
)
# Fit model
grid_search.fit(X, y)
# Hasil terbaik
print(f"Best parameters: {grid_search.best_params_}")
print(f"Best score: {grid_search.best_score_:.4f}")Grid ini menghasilkan 36 kombinasi (3 × 4 × 3). Dengan 5-fold cross-validation, total training sebanyak 180 kali. Proses ini komprehensif tetapi komputasinya mahal untuk dataset besar atau model kompleks.
Menggunakan RandomizedSearchCV untuk Efisiensi
RandomizedSearchCV mengambil pendekatan berbeda. Alih-alih mencoba semua kombinasi, metode ini mengambil sampel acak dari distribusi parameter yang kita tentukan. Pendekatan ini jauh lebih cepat dengan trade-off coverage yang dapat diterima.
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform
# Definisikan distribusi parameter
param_distributions = {
'n_estimators': randint(50, 500),
'max_depth': [3, 5, 7, 10, None],
'min_samples_split': randint(2, 20),
'min_samples_leaf': randint(1, 10),
'max_features': ['sqrt', 'log2', None]
}
# Inisialisasi RandomizedSearchCV
random_search = RandomizedSearchCV(
estimator=rf,
param_distributions=param_distributions,
n_iter=50, # Hanya 50 kombinasi acak
cv=5,
scoring='accuracy',
n_jobs=-1,
random_state=42,
verbose=1
)
# Fit model
random_search.fit(X, y)
print(f"Best parameters: {random_search.best_params_}")
print(f"Best score: {random_search.best_score_:.4f}")Dengan n_iter=50, kita hanya melakukan 250 training (50 × 5-fold) dibandingkan ribuan kombinasi yang mungkin ada. Keuntungan signifikan dalam runtime dengan hasil yang sering kali sebanding.
Strategi Memilih Metode yang Tepat
Deep Learning Bootcamp
A beginner-friendly, highly interactive bootcamp designed to take you from found...
Pemilihan antara kedua metode bergantung pada konteks:
Gunakan GridSearchCV ketika:
- Ruang parameter kecil dan dapat dikelola
- Setiap kombinasi harus dieksplorasi secara menyeluruh
- Komputasi tidak menjadi bottleneck
Gunakan RandomizedSearchCV ketika:
- Ruang parameter besar atau kontinu
- Waktu dan resource terbatas
- Perlu eksplorasi cepat sebelum fine-tuning
Best Practices dalam Hyperparameter Tuning
Definisikan ruang pencarian yang rasional. Jangan gunakan rentang yang terlalu luas tanpa pemahaman domain. Parameter seperti learning_rate biasanya berada dalam skala logaritmik, sementara n_estimators linear.
Gunakan Cross-Validation yang sesuai. cv=5 adalah default yang baik untuk sebagian besar kasus. Dataset kecil memerlukan cv yang lebih tinggi, sementara dataset besar dapat menggunakan cv=3 untuk efisiensi.
Simpan hasil untuk analisis. Kedua metode menyimpan seluruh history pencarian di atribut cv_results_. Analisis ini membantu memahami sensitivitas model terhadap parameter tertentu.
import pandas as pd
# Konversi hasil ke DataFrame
results_df = pd.DataFrame(random_search.cv_results_)
# Lihat top 5 kombinasi terbaik
top_results = results_df.nlargest(5, 'mean_test_score')
print(top_results[['params', 'mean_test_score', 'std_test_score']])Implementasi Production-Ready
Dalam environment production, kita sering menggabungkan kedua pendekatan. Mulai dengan RandomizedSearchCV untuk eksplorasi cepat, kemudian gunakan GridSearchCV pada area yang menjanjikan untuk fine-tuning final.
Selalu gunakan n_jobs=-1 untuk memanfaatkan semua CPU core. Parameter verbose=1 atau lebih tinggi memberikan progress tracking yang berguna untuk proses panjang.
Kesimpulan
GridSearchCV dan RandomizedSearchCV adalah tools fundamental untuk mengoptimalkan model machine learning. GridSearchCV memberikan exhaustive search dengan jaminan optimalitas lokal, sementara RandomizedSearchCV menawarkan efisiensi superior untuk ruang parameter besar. Pemilihan metode yang tepat bergantung pada trade-off antara komputasi dan eksplorasi yang dibutuhkan untuk use case spesifik.
Di Rumah Coding, kami membahas teknik hyperparameter tuning secara mendalam dalam kurikulum Machine Learning Bootcamp. Bergabunglah dengan program kami untuk mempelajari strategi optimization yang digunakan oleh praktisi industry.
Course Terkait
Deep Learning Bootcamp
A beginner-friendly, highly interactive bootcamp designed to take you from foundational concepts to deploying real-world Artificial Intelligence applications. Through a completely project-based approach, you will master the core of Deep Learning, Artificial Neural Networks, and Computer Vision using Python and TensorFlow, ultimately building a professional-grade AI web application for your portfolio.
GreenGuard: Intelligent Plant Disease Diagnosis Web App
- Interactive Image Upload UI: A clean, user-friendly interface built with Streamlit that supports drag-and-drop image uploads directly from a computer or mobile phone.
- Real-Time AI Inference: Utilizes a lightweight, optimized CNN model (like MobileNetV2) to process the image and return a diagnosis in seconds without heavy server load.
- Confidence Scoring Dashboard: Visually displays the model's prediction probability (e.g., "95% confident this is Tomato Late Blight") using interactive progress bars or charts.
LLM Bootcamp
This project-based bootcamp is designed for beginners to dive practically into the world of Large Language Models (LLMs). Through hands-on building, you will learn how to interact with top-tier AI APIs, master prompt engineering, orchestrate complex workflows using LangChain, and implement Retrieval-Augmented Generation (RAG) to query your own documents. By the end of this course, you will have the skills to build, test, and deploy a fully functional, custom AI web application.
Domain-Specific AI Knowledge Assistant
- Dynamic Document Processing: A sidebar interface allowing users to upload new PDF or TXT files, which the app automatically chunks, embeds, and stores in the vector database.
- Context-Aware Chat UI: A modern chat interface built with Streamlit that maintains conversation history, allowing users to ask follow-up questions naturally.
- Strict Guardrails (Anti-Hallucination): System instructions designed so the AI politely declines to answer questions that fall outside the context of the uploaded documents.
Machine Learning Bootcamp
A beginner-friendly, 7-week project-based bootcamp designed to take you from Python basics to deploying your first Machine Learning model. Through hands-on practice, you will master essential data manipulation, build predictive algorithms, and develop an end-to-end, industry-ready application to kickstart your career in data science.
End-to-End Student Success Predictor
- Automated Data Pipeline: A preprocessing script that automatically cleans missing values, encodes categorical data (like course type or student background), and scales numerical inputs.
- Predictive Engine: A tuned machine learning classification model (e.g., Random Forest) specifically optimized for high Recall, ensuring that "at-risk" students are not missed.
- Interactive Web Dashboard: A user-friendly Streamlit interface featuring a sidebar where instructors can manually input a student's study hours, quiz scores, and login frequency to get an instant pass/fail probability.