Heim  >  Artikel  >  Backend-Entwicklung  >  ML-Modellauswahl.

ML-Modellauswahl.

Barbara Streisand
Barbara StreisandOriginal
2024-09-25 06:30:06703Durchsuche

ML Model Selection.

1. Einführung

In diesem Artikel erfahren Sie, wie Sie aus mehreren Modellen mit unterschiedlichen Hyperparametern das beste Modell auswählen. In einigen Fällen können wir über mehr als 50 verschiedene Modelle verfügen. Es ist wichtig zu wissen, wie Sie eines auswählen, um das Modell mit der besten Leistung für Ihren Datensatz zu erhalten .

Wir werden die Modellauswahl sowohl durch Auswahl des besten Lernalgorithmus als auch seiner besten Hyperparameter durchführen.

Aber zuerst: Was sind Hyperparameter? Dies sind die zusätzlichen Einstellungen, die vom Benutzer festgelegt werden und sich darauf auswirken, wie das Modell seine Parameter lernt. Parameter hingegen sind das, was Modelle während des Trainingsprozesses lernen.

2. Verwendung einer umfassenden Suche.

Umfassende Suche beinhaltet die Auswahl des besten Modells durch die Suche über eine Reihe von Hyperparametern. Dazu nutzen wir scikit-learns GridSearchCV.

So funktioniert GridSearchCV:

  1. Der Benutzer definiert Sätze möglicher Werte für einen oder mehrere Hyperparameter.
  2. GridSearchCV trainiert ein Modell mit jedem Wert und/oder jeder Wertekombination.
  3. Das Modell mit der besten Leistung wird als bestes Modell ausgewählt.

Beispiel
Wir können eine logistische Regression als unseren Lernalgorithmus einrichten und zwei Hyperparameter (C und die Regularisierungsstrafe) optimieren. Wir können auch zwei Parameter angeben: den Solver und die maximale Iteration.

Jetzt trainieren wir für jede Kombination aus C- und Regularisierungsstrafenwerten das Modell und bewerten es mithilfe einer k-fachen Kreuzvalidierung.
Da wir 10 mögliche Werte von C haben, sind 2 mögliche Werte von reg. Strafe und 5 Falten haben wir insgesamt (10 x 2 x 5 = 100) Kandidatenmodelle, aus denen das beste ausgewählt wird.

# 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

Das beste Modell finden:

# 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. Verwenden der randomisierten Suche.

Dies wird häufig verwendet, wenn Sie eine rechnerisch günstigere Methode als eine umfassende Suche zur Auswahl des besten Modells wünschen.

Es ist erwähnenswert, dass der Grund dafür ist, dass RandomizedSearchCV nicht von Natur aus schneller ist als GridSearchCV, aber oft eine mit GridSearchCV vergleichbare Leistung in kürzerer Zeit erreicht, nur indem weniger Kombinationen getestet werden.

So funktioniert RandomizedSearchCV:

  1. Der Benutzer stellt Hyperparameter/Verteilungen (z. B. normal, gleichmäßig) bereit.
  2. Die Algorithmen durchsuchen zufällig eine bestimmte Anzahl zufälliger Kombinationen der angegebenen Hyperparameterwerte ohne Ersatz.

Beispiel

# 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.

Das beste Modell finden:

# 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

Hinweis: Die Anzahl der trainierten Kandidatenmodelle wird in den Einstellungen für n_iter (Anzahl der Iterationen) angegeben.

4. Auswahl der besten Modelle aus mehreren Lernalgorithmen.

In diesem Teil schauen wir uns an, wie man das beste Modell auswählt, indem man eine Reihe von Lernalgorithmen und ihre jeweiligen Hyperparameter durchsucht.

Wir können dies tun, indem wir einfach ein Wörterbuch der Kandidaten-Lernalgorithmen und ihrer Hyperparameter erstellen, um es als Suchraum für GridSearchCV zu verwenden.

Schritte:

  1. Wir können einen Suchraum definieren, der zwei Lernalgorithmen enthält.
  2. Wir spezifizieren die Hyperparameter und definieren ihre Kandidatenwerte im Format Klassifikator[Hyperparametername]_.
# 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'))])

Das beste Modell:
Nachdem die Suche abgeschlossen ist, können wir best_estimator_ verwenden, um den Lernalgorithmus und die Hyperparameter des besten Modells anzuzeigen.

5. Auswahl des besten Modells bei der Vorverarbeitung.

Manchmal möchten wir möglicherweise einen Vorverarbeitungsschritt in die Modellauswahl einbeziehen.
Die beste Lösung besteht darin, eine Pipeline zu erstellen, die den Vorverarbeitungsschritt und alle seine Parameter enthält:

Die erste Herausforderung:
GridSeachCv verwendet eine Kreuzvalidierung, um das Modell mit der höchsten Leistung zu ermitteln.

Bei der Kreuzvalidierung geben wir jedoch vor, dass die Falte, die als Testsatz angezeigt wird, nicht sichtbar ist und daher nicht Teil der Anpassung irgendwelcher Vorverarbeitungsschritte (z. B. Skalierung oder Standardisierung) ist.

Aus diesem Grund müssen die Vorverarbeitungsschritte Teil der von GridSearchCV durchgeführten Aktionen sein.

Die Lösung
Scikit-learn stellt die FeatureUnion bereit, die es uns ermöglicht, mehrere Vorverarbeitungsaktionen ordnungsgemäß zu kombinieren.
Schritte:

  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.

Das obige ist der detaillierte Inhalt vonML-Modellauswahl.. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn