>  기사  >  백엔드 개발  >  ML 모델 선택.

ML 모델 선택.

Barbara Streisand
Barbara Streisand원래의
2024-09-25 06:30:06703검색

ML Model Selection.

1. 소개

이 기사에서는 다양한 하이퍼매개변수가 있는 여러 모델 중에서 가장 적합한 모델을 선택하는 방법을 알아봅니다. 어떤 경우에는 50개 이상의 서로 다른 모델이 있을 수 있습니다. 하나를 선택하는 방법이 데이터세트에 가장 적합한 모델을 얻는 데 중요하다는 것을 알고 있습니다. .

최고의 학습 알고리즘과 최고의 하이퍼파라미터를 모두 선택하여 모델을 선택합니다.

그럼 먼저 초매개변수란 무엇일까요? 이는 사용자가 설정하는 추가 설정이며 모델이 해당 매개변수를 학습하는 방법에 영향을 미칩니다. 반면 매개변수는 모델이 학습 과정에서 학습하는 내용입니다.

2. 철저한 검색 사용.

완전한 검색은 다양한 하이퍼파라미터를 검색하여 가장 적합한 모델을 선택하는 것입니다. 이를 위해 우리는 scikit-learn의 GridSearchCV를 사용합니다.

GridSearchCV 작동 방식:

  1. 사용자는 하나 이상의 하이퍼파라미터에 대해 가능한 값 세트를 정의합니다.
  2. GridSearchCV는 모든 값 및/또는 값의 조합을 사용하여 모델을 학습합니다.
  3. 가장 좋은 성능을 발휘한 모델을 최우수 모델로 선정합니다.


학습 알고리즘으로 로지스틱 회귀를 설정하고 두 개의 하이퍼 매개변수(C 및 정규화 페널티)를 조정할 수 있습니다. 솔버와 최대 반복이라는 두 가지 매개변수를 지정할 수도 있습니다.

이제 C와 정규화 페널티 값의 각 조합에 대해 모델을 훈련하고 k-겹 교차 검증을 사용하여 평가합니다.
C에는 10개의 가능한 값이 있고 reg에는 2개의 가능한 값이 있습니다. 페널티와 5겹을 거쳐 총 (10 x 2 x 5 = 100)개의 후보 모델이 있으며 그 중에서 가장 좋은 모델이 선택됩니다.

# Load libraries
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create logistic regression
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Create range of candidate penalty hyperparameter values
penalty = ['l1','l2']

# Create range of candidate regularization hyperparameter values
C = np.logspace(0, 4, 10)

# Create dictionary of hyperparameter candidates
hyperparameters = dict(C=C, penalty=penalty)

# Create grid search
gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0)

# Fit grid search
best_model = gridsearch.fit(features, target)

# Show the best model
print(best_model.best_estimator_)

# LogisticRegression(C=7.742636826811269, max_iter=500, penalty='l1',
solver='liblinear') # Result

최고의 모델 확보:

# View best hyperparameters
print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])
print('Best C:', best_model.best_estimator_.get_params()['C'])

# Best Penalty: l1 #Result
# Best C: 7.742636826811269 # Result

3. 무작위 검색 사용.

가장 좋은 모델을 선택하기 위해 완전 검색보다 계산적으로 더 저렴한 방법을 원할 때 일반적으로 사용됩니다.

RandomizedSearchCV가 본질적으로 GridSearchCV보다 빠르지는 않지만 더 적은 조합을 테스트하여 더 짧은 시간에 GridSearchCV와 비슷한 성능을 달성하는 이유는 주목할 가치가 있습니다.

RandomizedSearchCV 작동 방식:

  1. 사용자는 하이퍼파라미터/분포(예: 정규, 균일)를 제공합니다.
  2. 알고리즘은 주어진 하이퍼파라미터 값의 특정 개수의 무작위 조합을 대체 없이 무작위로 검색합니다.


# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create logistic regression
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Create range of candidate regularization penalty hyperparameter values
penalty = ['l1', 'l2']

# Create distribution of candidate regularization hyperparameter values
C = uniform(loc=0, scale=4)

# Create hyperparameter options
hyperparameters = dict(C=C, penalty=penalty)

# Create randomized search
randomizedsearch = RandomizedSearchCV(
logistic, hyperparameters, random_state=1, n_iter=100, cv=5, verbose=0,
n_jobs=-1)

# Fit randomized search
best_model = randomizedsearch.fit(features, target)

# Print best model
print(best_model.best_estimator_)

# LogisticRegression(C=1.668088018810296, max_iter=500, penalty='l1',
solver='liblinear') #Result.

최고의 모델 확보:

# View best hyperparameters
print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])
print('Best C:', best_model.best_estimator_.get_params()['C'])

# Best Penalty: l1 # Result
# Best C: 1.668088018810296 # Result

참고: 훈련된 후보 모델 수는 n_iter(반복 횟수) 설정에서 지정됩니다.

4. 다중 학습 알고리즘에서 최상의 모델 선택.

이번 부분에서는 다양한 학습 알고리즘과 각각의 하이퍼파라미터를 검색하여 최적의 모델을 선택하는 방법을 살펴보겠습니다.

GridSearchCV의 검색 공간으로 사용할 후보 학습 알고리즘과 하이퍼파라미터의 사전을 생성하면 됩니다.

단계:

  1. 두 가지 학습 알고리즘을 포함하는 검색 공간을 정의할 수 있습니다.
  2. 초매개변수를 지정하고 분류자[초매개변수 이름]_ 형식을 사용하여 해당 후보 값을 정의합니다.
# Load libraries
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline

# Set random seed
np.random.seed(0)

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create a pipeline
pipe = Pipeline([("classifier", RandomForestClassifier())])

# Create dictionary with candidate learning algorithms and their hyperparameters
search_space = [{"classifier": [LogisticRegression(max_iter=500,
solver='liblinear')],
"classifier__penalty": ['l1', 'l2'],
"classifier__C": np.logspace(0, 4, 10)},
{"classifier": [RandomForestClassifier()],
"classifier__n_estimators": [10, 100, 1000],
"classifier__max_features": [1, 2, 3]}]

# Create grid search
gridsearch = GridSearchCV(pipe, search_space, cv=5, verbose=0)

# Fit grid search
best_model = gridsearch.fit(features, target)

# Print best model
print(best_model.best_estimator_)

# Pipeline(steps=[('classifier',
                 LogisticRegression(C=7.742636826811269, max_iter=500,
                      penalty='l1', solver='liblinear'))])

최고의 모델:
검색이 완료된 후 best_estimator_를 사용하여 최상의 모델의 학습 알고리즘과 하이퍼파라미터를 볼 수 있습니다.

5. 전처리 시 최적의 모델 선택.

때때로 모델 선택 중에 전처리 단계를 포함하고 싶을 수도 있습니다.
가장 좋은 해결책은 전처리 단계와 해당 매개변수를 포함하는 파이프라인을 생성하는 것입니다.

첫 번째 도전:
GridSeachCv는 교차 검증을 사용하여 성능이 가장 높은 모델을 결정합니다.

그러나 교차 검증에서는 테스트 세트에 접힌 부분이 보이지 않는 것처럼 가정하므로 전처리 단계(예: 크기 조정 또는 표준화)를 맞추는 데 일부가 아닙니다.

이러한 이유로 전처리 단계는 GridSearchCV가 수행하는 작업 집합의 일부여야 합니다.

솔루션
Scikit-learn은 여러 전처리 작업을 적절하게 결합할 수 있는 FeatureUnion을 제공합니다.
단계:

  1. We use _FeatureUnion _to combine two preprocessing steps: standardize the feature values(StandardScaler) and principal component analysis(PCA) - this object is called the preprocess and contains both of our preprocessing steps.
  2. Next we include preprocess in our pipeline with our learning algorithm.

This allows us to outsource the proper handling of fitting, transforming, and training the models with combinations of hyperparameters to scikit-learn.

Second Challenge:
Some preprocessing methods such as PCA have their own parameters, dimensionality reduction using PCA requires the user to define the number of principal components to use to produce the transformed features set. Ideally we would choose the number of components that produces a model with the greatest performance for some evaluation test metric.
Solution.
In scikit-learn when we include candidate component values in the search space, they are treated like any other hyperparameter to be searched over.

# Load libraries
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# Set random seed
np.random.seed(0)

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create a preprocessing object that includes StandardScaler features and PCA
preprocess = FeatureUnion([("std", StandardScaler()), ("pca", PCA())])

# Create a pipeline
pipe = Pipeline([("preprocess", preprocess),
               ("classifier", LogisticRegression(max_iter=1000,
               solver='liblinear'))])

# Create space of candidate values
search_space = [{"preprocess__pca__n_components": [1, 2, 3],
"classifier__penalty": ["l1", "l2"],
"classifier__C": np.logspace(0, 4, 10)}]

# Create grid search
clf = GridSearchCV(pipe, search_space, cv=5, verbose=0, n_jobs=-1)

# Fit grid search
best_model = clf.fit(features, target)

# Print best model
print(best_model.best_estimator_)

# Pipeline(steps=[('preprocess',
     FeatureUnion(transformer_list=[('std', StandardScaler()),
                                    ('pca', PCA(n_components=1))])),
    ('classifier',
    LogisticRegression(C=7.742636826811269, max_iter=1000,
                      penalty='l1', solver='liblinear'))]) # Result


After the model selection is complete we can view the preprocessing values that produced the best model.

Preprocessing steps that produced the best modes

# View best n_components

best_model.best_estimator_.get_params() 
# ['preprocess__pca__n_components'] # Results

5. Speeding Up Model Selection with Parallelization.

That time you need to reduce the time it takes to select a model.
We can do this by training multiple models simultaneously, this is done by using all the cores in our machine by setting n_jobs=-1

# Load libraries
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create logistic regression
logistic = linear_model.LogisticRegression(max_iter=500, 
                                           solver='liblinear')

# Create range of candidate regularization penalty hyperparameter values
penalty = ["l1", "l2"]

# Create range of candidate values for C
C = np.logspace(0, 4, 1000)

# Create hyperparameter options
hyperparameters = dict(C=C, penalty=penalty)

# Create grid search
gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, n_jobs=-1, 
                             verbose=1)

# Fit grid search
best_model = gridsearch.fit(features, target)

# Print best model
print(best_model.best_estimator_)

# Fitting 5 folds for each of 2000 candidates, totalling 10000 fits
# LogisticRegression(C=5.926151812475554, max_iter=500, penalty='l1',
                                                  solver='liblinear')

6. Speeding Up Model Selection ( Algorithm Specific Methods).

This a way to speed up model selection without using additional compute power.

This is possible because scikit-learn has model-specific cross-validation hyperparameter tuning.

Sometimes the characteristics of a learning algorithms allows us to search for the best hyperparameters significantly faster.

Example:
LogisticRegression is used to conduct a standard logistic regression classifier.
LogisticRegressionCV implements an efficient cross-validated logistic regression classifier that can identify the optimum value of the hyperparameter C.

# Load libraries
from sklearn import linear_model, datasets

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create cross-validated logistic regression
logit = linear_model.LogisticRegressionCV(Cs=100, max_iter=500,
                                            solver='liblinear')

# Train model
logit.fit(features, target)

# Print model
print(logit)

# LogisticRegressionCV(Cs=100, max_iter=500, solver='liblinear')

Note:A major downside to LogisticRegressionCV is that it can only search a range of values for C. This limitation is common to many of scikit-learn's model-specific cross-validated approaches.

I hope this Article was helpful in creating a quick overview of how to select a machine learning model.

위 내용은 ML 모델 선택.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.