在Scikit-learn中,可以使用GridSearchCV或RandomizedSearchCV來實現模型的自我優化。這兩個方法可以幫助我們在指定的參數范圍內搜索最優的模型參數。
示例代碼如下:
from sklearn.model_selection import GridSearchCV
param_grid = {
'param1': [value1, value2, ...],
'param2': [value1, value2, ...],
...
}
grid_search = GridSearchCV(estimator=your_model, param_grid=param_grid, cv=5)
grid_search.fit(X_train, y_train)
best_params = grid_search.best_params_
best_model = grid_search.best_estimator_
示例代碼如下:
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_dist = {
'param1': randint(1, 100),
'param2': randint(1, 100),
...
}
random_search = RandomizedSearchCV(estimator=your_model, param_distributions=param_dist, n_iter=10, cv=5)
random_search.fit(X_train, y_train)
best_params = random_search.best_params_
best_model = random_search.best_estimator_
通過使用GridSearchCV或RandomizedSearchCV,我們可以有效地搜索最優的模型參數,從而實現模型的自我優化。