ML 모델 선택.
1. 소개
이 기사에서는 다양한 하이퍼매개변수가 있는 여러 모델 중에서 가장 적합한 모델을 선택하는 방법을 알아봅니다. 어떤 경우에는 50개 이상의 서로 다른 모델이 있을 수 있습니다. 하나를 선택하는 방법이 데이터세트에 가장 적합한 모델을 얻는 데 중요하다는 것을 알고 있습니다. .
최고의 학습 알고리즘과 최고의 하이퍼파라미터를 모두 선택하여 모델을 선택합니다.
그럼 먼저 초매개변수란 무엇일까요? 이는 사용자가 설정하는 추가 설정이며 모델이 해당 매개변수를 학습하는 방법에 영향을 미칩니다. 반면 매개변수는 모델이 학습 과정에서 학습하는 내용입니다.
2. 철저한 검색 사용.
완전한 검색은 다양한 하이퍼파라미터를 검색하여 가장 적합한 모델을 선택하는 것입니다. 이를 위해 우리는 scikit-learn의 GridSearchCV를 사용합니다.
GridSearchCV 작동 방식:
- 사용자는 하나 이상의 하이퍼파라미터에 대해 가능한 값 세트를 정의합니다.
- GridSearchCV는 모든 값 및/또는 값의 조합을 사용하여 모델을 학습합니다.
- 가장 좋은 성능을 발휘한 모델을 최우수 모델로 선정합니다.
예
학습 알고리즘으로 로지스틱 회귀를 설정하고 두 개의 하이퍼 매개변수(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 작동 방식:
- 사용자는 하이퍼파라미터/분포(예: 정규, 균일)를 제공합니다.
- 알고리즘은 주어진 하이퍼파라미터 값의 특정 개수의 무작위 조합을 대체 없이 무작위로 검색합니다.
예
# 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의 검색 공간으로 사용할 후보 학습 알고리즘과 하이퍼파라미터의 사전을 생성하면 됩니다.
단계:
- 두 가지 학습 알고리즘을 포함하는 검색 공간을 정의할 수 있습니다.
- 초매개변수를 지정하고 분류자[초매개변수 이름]_ 형식을 사용하여 해당 후보 값을 정의합니다.
# 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을 제공합니다.
단계:
- 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.
- 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화
