12.1. Wybór najlepszych modeli przy użyciu wyczerpującego wyszukiwania

# Wczytanie bibliotek.
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Zdefiniowanie regresji logistycznej.
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Zdefiniowanie zakresu wartości hiperparametru penalty.
penalty = ['l1', 'l2']

# Zdefiniowanie zakresu wartości hiperparametru regularyzacji.
C = np.logspace(0, 4, 10)

# Utworzenie słownika wartości hiperparametrów.
hyperparameters = dict(C=C, penalty=penalty)

# Zdefiniowanie siatki przeszukiwania.
gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0)

# Dopasowanie siatki przeszukiwania.
best_model = gridsearch.fit(features, target)

# Wyświetlenie najlepszego modelu.
print(best_model.best_estimator_)

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





np.logspace(0, 4, 10)

array([  1.00000000e+00,   2.78255940e+00,   7.74263683e+00,
         2.15443469e+01,   5.99484250e+01,   1.66810054e+02,
         4.64158883e+02,   1.29154967e+03,   3.59381366e+03,
         1.00000000e+04])





# Wyświetlenie najlepszych hiperparametrów.
print('Najlepsza wartość parametru penalty:', best_model.best_estimator_.get_params()['penalty'])
print('Najlepsza wartość parametru C:', best_model.best_estimator_.get_params()['C'])

Najlepsza wartość parametru penalty: l1
Najlepsza wartość parametru C: 7.742636826811269





# Prognozowany wektor docelowy.
best_model.predict(features)

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
           2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])





12.2. Wybór najlepszych modeli za pomocą przeszukiwania losowego

# Wczytanie bibliotek.
from scipy.stats import uniform
from sklearn import linear_model, datasets
from sklearn.model_selection import RandomizedSearchCV

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Zdefiniowanie regresji logistycznej.
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Zdefiniowanie zakresu wartości hiperparametru penalty.
penalty = ['l1', 'l2']

# Zdefiniowanie zakresu wartości hiperparametru regularyzacji.
C = uniform(loc=0, scale=4)

# Zdefiniowanie opcji hiperparametru.
hyperparameters = dict(C=C, penalty=penalty)

# Zdefiniowanie przeszukiwania losowego.
randomizedsearch = RandomizedSearchCV(
    logistic, hyperparameters, random_state=1, n_iter=100, cv=5, verbose=0,
    n_jobs=-1)

# Dopasowanie przeszukiwania losowego.
best_model = randomizedsearch.fit(features, target)


# Wyświetlenie najlepszego modelu.
print(best_model.best_estimator_)
LogisticRegression(C=1.668088018810296, max_iter=500, penalty='l1',
                   solver='liblinear')





# Zdefiniowanie rozkładu jednorodnego w przedziale od 0 do 4 i pobranie 10 wartości.
uniform(loc=0, scale=4).rvs(10)

array([3.95211699, 0.30693116, 2.88237794, 3.00392864, 0.43964702,
           1.46670526, 0.27841863, 2.56541664, 2.66475584, 0.79611958])





# Wyświetlenie najlepszych hiperparametrów.
print('Najlepsza wartość parametru penalty:', best_model.best_estimator_.get_params()['penalty'])
print('Najlepsza wartość parametru C:', best_model.best_estimator_.get_params()['C'])

Najlepsza wartość parametru penalty: l1
Najlepsza wartość parametru C: 1.668088018810296





# Prognozowany wektor docelowy.
best_model.predict(features)

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2,
           2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])





12.3. Wybór najlepszych modeli z wielu algorytmów uczenia maszynowego

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

# Zdefiniowanie wartości zalążka.
np.random.seed(0)

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Utworzenia egzemplarza typu Pipeline.
pipe = Pipeline([("classifier", RandomForestClassifier())])

# Utworzenie słownika wybranych algorytmów uczenia maszynowego i ich hiperparametrów.
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]}]

# Zdefiniowanie siatki przeszukiwania.
gridsearch = GridSearchCV(pipe, search_space, cv=5, verbose=0)

# Dopasowanie siatki przeszukiwania.
best_model = gridsearch.fit(features, target)

# Wyświetlenie najlepszego modelu.
print(best_model.best_estimator_)
Pipeline(steps=[('classifier',
                 LogisticRegression(C=7.742636826811269, max_iter=500,
                                    penalty='l1', solver='liblinear'))])





{'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]}





# Wyświetlenie najlepszego modelu.
print(best_model.best_estimator_.get_params()["classifier"])

LogisticRegression(C=7.742636826811269, max_iter=100, penalty='l1',
          solver='liblinear')





# Prognozowany wektor docelowy.
best_model.predict(features)

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
           2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])





12.4. Wybór najlepszych modeli na etapie przygotowywania danych

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

# Zdefiniowanie wartości zalążka.
np.random.seed(0)

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Utworzenie obiektu przetwarzania danych obejmującego egzemplarze typów StandardScaler i PCA.
preprocess = FeatureUnion([("std", StandardScaler()), ("pca", PCA())])

# Utworzenia egzemplarza typu Pipeline.
pipe = Pipeline([("preprocess", preprocess),
                 ("classifier", LogisticRegression(max_iter=1000,
                         solver='liblinear'))])

# Przygotowanie miejsca dla wartości.
search_space = [{"preprocess__pca__n_components": [1, 2, 3],
                 "classifier__penalty": ["l1", "l2"],
                 "classifier__C": np.logspace(0, 4, 10)}]

# Zdefiniowanie siatki przeszukiwania.
clf = GridSearchCV(pipe, search_space, cv=5, verbose=0, n_jobs=-1)

# Dopasowanie siatki przeszukiwania.
best_model = clf.fit(features, target)

# Wyświetlenie najlepszego modelu.
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'))])





# Wyświetlenie najlepszego modelu.
best_model.best_estimator_.get_params()['preprocess__pca__n_components']

1





12.5. Przyspieszanie wyboru modelu za pomocą równoległości

# Wczytanie bibliotek.
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Zdefiniowanie regresji logistycznej.
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Zdefiniowanie zakresu wartości hiperparametru penalty.
penalty = ["l1", "l2"]

# Zdefiniowanie zakresu potencjalnych wartości dla C.
C = np.logspace(0, 4, 1000)

# Zdefiniowanie opcji hiperparametru.
hyperparameters = dict(C=C, penalty=penalty)

# Zdefiniowanie siatki przeszukiwania.
gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, n_jobs=-1, verbose=1)

# Dopasowanie siatki przeszukiwania.
best_model = gridsearch.fit(features, target)

# Wyświetlenie najlepszego modelu.
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')





# Zdefiniowanie siatki przeszukiwania z użyciem tylko jednego rdzenia.
clf = GridSearchCV(logistic, hyperparameters, cv=5, n_jobs=1, verbose=1)

# Dopasowanie siatki przeszukiwania.
best_model = clf.fit(features, target)

# Wyświetlenie najlepszego modelu.
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')





12.6. Przyspieszanie wyboru modelu przy użyciu metod charakterystycznych dla algorytmu

# Wczytanie bibliotek.
from sklearn import linear_model, datasets

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Zdefiniowanie sprawdzianu krzyżowego regresji logistycznej.
logit = linear_model.LogisticRegressionCV(Cs=100, max_iter=500,
           solver='liblinear')

# Wytrenowanie modelu.
logit.fit(features, target)

# Wyświetlenie modelu.
print(logit)

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





12.7. Ocena wydajności po wyborze modelu

# Wczytanie bibliotek.
import numpy as np
from sklearn import linear_model, datasets
from sklearn.model_selection import GridSearchCV, cross_val_score

# Wczytanie danych.
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Zdefiniowanie regresji logistycznej.
logistic = linear_model.LogisticRegression(max_iter=500, solver='liblinear')

# Zdefiniowanie zakresu 20 potencjalnych wartości dla C.
C = np.logspace(0, 4, 20)

# Zdefiniowanie opcji hiperparametru.
hyperparameters = dict(C=C)

# Zdefiniowanie siatki przeszukiwania.
gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, n_jobs=-1, verbose=0)

# Przeprowadzenie zagnieżdżonego sprawdzianu krzyżowego i wyświetlenie wartości średniej.
cross_val_score(gridsearch, features, target).mean()

0.9733333333333334





gridsearch = GridSearchCV(logistic, hyperparameters, cv=5, verbose=1)




best_model = gridsearch.fit(features, target)

Fitting 5 folds for each of 20 candidates, totalling 100 fits





scores = cross_val_score(gridsearch, features, target)

Fitting 5 folds for each of 20 candidates, totalling 100 fits
Fitting 5 folds for each of 20 candidates, totalling 100 fits
Fitting 5 folds for each of 20 candidates, totalling 100 fits
Fitting 5 folds for each of 20 candidates, totalling 100 fits
Fitting 5 folds for each of 20 candidates, totalling 100 fits
