Monday, May 23, 2022

One-Class Classification Algorithms for Imbalanced Datasets

 ======================================

Одноклассовые машины опорных векторов

======================================

Алгоритм машины опорных векторов, или SVM, первоначально разработанный для бинарной классификации, можно использовать для классификации одного класса.

Если используется для несбалансированной классификации, рекомендуется оценить стандартную SVM и взвешенную SVM в наборе данных, прежде чем тестировать версию с одним классом.При моделировании одного класса алгоритм фиксирует плотность большинства классов и классифицирует примеры на экстремумах функции плотности как выбросы. Эта модификация SVM называется One-Class SVM.

Основное отличие от стандартного SVM заключается в том, что он подходит неконтролируемым образом и не предоставляет обычных гиперпараметров для настройки поля, как C. Вместо этого он предоставляет гиперпараметр «nu», который управляет чувствительностью опорных векторов и должен быть настроен на приблизительное соотношение выбросов в данных, например. 0,01%


(.env) boris@boris-All-Series:~/ONECLASS$ cat oneClassSVM.py

# one-class svm for imbalanced binary classification

from sklearn.datasets import make_classification

from sklearn.model_selection import train_test_split

from sklearn.metrics import f1_score

from sklearn.svm import OneClassSVM

# generate dataset

X, y = make_classification(n_samples=10000, n_features=2, n_redundant=0,

n_clusters_per_class=1, weights=[0.999], flip_y=0, random_state=4)

# split into train/test sets

trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2, stratify=y)

# define outlier detection model

model = OneClassSVM(gamma='scale', nu=0.01)

# fit on majority class

trainX = trainX[trainy==0]

model.fit(trainX)

# detect outliers in the test set

yhat = model.predict(testX)

# mark inliers 1, outliers -1

testy[testy == 1] = -1

testy[testy == 0] = 1

# calculate score

score = f1_score(testy, yhat, pos_label=-1)

print('F1 Score: %.3f' % score)

(.env) boris@boris-All-Series:~/ONECLASS$ python3 oneClassSVM.py

F1 Score: 0.123

(.env) boris@boris-All-Series:~/ONECLASS$ cat plot_oneclassSVM.py

"""

==========================================

One-class SVM with non-linear kernel (RBF)

==========================================

"""


import numpy as np

import matplotlib.pyplot as plt

import matplotlib.font_manager

from sklearn import svm


xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500))

# Generate train data

X = 0.3 * np.random.randn(100, 2)

X_train = np.r_[X + 2, X - 2]

# Generate some regular novel observations

X = 0.3 * np.random.randn(20, 2)

X_test = np.r_[X + 2, X - 2]

# Generate some abnormal novel observations

X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))


# fit the model

clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)

clf.fit(X_train)

y_pred_train = clf.predict(X_train)

y_pred_test = clf.predict(X_test)

y_pred_outliers = clf.predict(X_outliers)

n_error_train = y_pred_train[y_pred_train == -1].size

n_error_test = y_pred_test[y_pred_test == -1].size

n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size


# plot the line, the points, and the nearest vectors to the plane

Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)


plt.title("Novelty Detection")

plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu)

a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors="darkred")

plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors="palevioletred")


s = 40

b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c="white", s=s, edgecolors="k")

b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c="blueviolet", s=s, edgecolors="k")

c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c="gold", s=s, edgecolors="k")

plt.axis("tight")

plt.xlim((-5, 5))

plt.ylim((-5, 5))

plt.legend(

    [a.collections[0], b1, b2, c],

    [

        "learned frontier",

        "training observations",

        "new regular observations",

        "new abnormal observations",

    ],

    loc="upper left",

    prop=matplotlib.font_manager.FontProperties(size=11),

)

plt.xlabel(

    "error train: %d/200 ; errors novel regular: %d/40 ; errors novel abnormal: %d/40"

    % (n_error_train, n_error_test, n_error_outliers)

)

plt.show()















================================

ИзоляцияЛес (IsolationForest)

================================

IsolationForest «изолирует» наблюдения, случайным образом выбирая признак, а затем случайным образом выбирая значение разделения между максимальным и минимальным значениями выбранного признака.Поскольку рекурсивное разбиение может быть представлено древовидной структурой, количество разбиений, необходимых для выделения выборки, эквивалентно длине пути от корневого узла до конечного узла.Эта длина пути, усредненная по лесу таких случайных деревьев, является мерой нормальности и нашей решающей функцией.

Случайное разбиение дает заметные более короткие пути для аномалий. Следовательно, когда лес случайных деревьев вместе дает более короткие пути для конкретных выборок, они, скорее всего, будут аномалиями.


(.env) boris@boris-All-Series:~/ONECLASS$ cat plot_isolation_forest.py

import numpy as np

import matplotlib.pyplot as plt

from sklearn.ensemble import IsolationForest


rng = np.random.RandomState(42)


# Generate train data

X = 0.3 * rng.randn(100, 2)

X_train = np.r_[X + 2, X - 2]

# Generate some regular novel observations

X = 0.3 * rng.randn(20, 2)

X_test = np.r_[X + 2, X - 2]

# Generate some abnormal novel observations

X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))


# fit the model

clf = IsolationForest(max_samples=100, random_state=rng)

clf.fit(X_train)

y_pred_train = clf.predict(X_train)

y_pred_test = clf.predict(X_test)

y_pred_outliers = clf.predict(X_outliers)


# plot the line, the samples, and the nearest vectors to the plane

xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))

Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)


plt.title("IsolationForest")

plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)


b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c="white", s=20, edgecolor="k")

b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c="green", s=20, edgecolor="k")

c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c="red", s=20, edgecolor="k")

plt.axis("tight")

plt.xlim((-5, 5))

plt.ylim((-5, 5))

plt.legend(

    [b1, b2, c],

    ["training observations", "new regular observations", "new abnormal observations"],

    loc="upper left",

)

plt.show()















Комбинация источников по One-Class Classification Algorithms for Imbalanced Datasets, включая

https://machinelearningmastery.com/one-class-classification-algorithms/


Friday, May 20, 2022

Create PyQt5 plots with the popular Python plotting library

Сначала мы импортируем виджет панели инструментов из matplotlib.backends.backend_qt5agg.NavigationToolbar2QT, переименовав его в более простое имя NavigationToolbar. Мы создаем экземпляр панели инструментов, вызывая NavigationToolbar с двумя параметрами: сначала объект холста sc, а затем родитель для панели инструментов, в данном случае сам объект MainWindow. Передача холста связывает с ним созданную панель инструментов, позволяя управлять ею. Результирующий объект панели инструментов сохраняется в переменной панели инструментов.

Нам нужно добавить в окно два виджета, один над другим, поэтому мы используем QVBoxLayout. Сначала мы добавляем нашу панель виджетов панели инструментов, а затем виджет холста sc в этот макет. Наконец, мы устанавливаем этот макет в наш простой контейнер макета виджета, который устанавливается в качестве центрального виджета для окна.

Запуск приведенного ниже кода создаст макет окна (снапшоты в конце поста) , показывающий график внизу и элементы управления вверху в виде панели инструментов.

(.env) boris@boris-All-Series:~/QWIDIGET$ cat  QtWidgets1.py

import sys

import matplotlib

matplotlib.use('Qt5Agg')

from PyQt5 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar

from matplotlib.figure import Figure

class MplCanvas(FigureCanvasQTAgg):

    def __init__(self, parent=None, width=5, height=4, dpi=100):

        fig = Figure(figsize=(width, height), dpi=dpi)

        self.axes = fig.add_subplot(111)

        super(MplCanvas, self).__init__(fig)

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):

        super(MainWindow, self).__init__(*args, **kwargs)

        sc = MplCanvas(self, width=5, height=4, dpi=100)

        sc.axes.plot([0,1,2,3,4], [10,1,20,3,40])

        # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second.

        toolbar = NavigationToolbar(sc, self)

        layout = QtWidgets.QVBoxLayout()

        layout.addWidget(toolbar)

        layout.addWidget(sc)

        # Create a placeholder widget to hold our toolbar and canvas.

        widget = QtWidgets.QWidget()

        widget.setLayout(layout)

        self.setCentralWidget(widget)

        self.show()

app = QtWidgets.QApplication(sys.argv)

w = MainWindow()

app.exec_()

Кнопки, предоставляемые NavigationToolbar2QT, позволяют выполнять следующие действия:

Home, Back/Forward, Pan & Zoom, которые используются для навигации по графикам. Кнопки «Назад/Вперед» могут перемещаться назад и вперед по шагам навигации, например, увеличение масштаба и последующее нажатие «Назад» вернет к предыдущему масштабу. Дом возвращается в исходное состояние сюжета.


Конфигурация поля/позиции графика, которая может регулировать график в окне.

Редактор стилей осей/кривых, в котором можно изменять названия графиков и масштабы осей, а также устанавливать цвета и стили линий графика. При выборе цвета используется палитра цветов по умолчанию для платформы, что позволяет выбирать любые доступные цвета.

Сохранить, чтобы сохранить полученную фигуру как изображение (все форматы, поддерживаемые Matplotlib).














































































































Пример с параболами 2-ой и 3-ей степени

(.env) boris@boris-All-Series:~/PYQT5WG$ cat matplotQWD1.py
import sys
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import numpy as np

class MplCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        super(MplCanvas, self).__init__(fig)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        sc = MplCanvas(self, width=5, height=4, dpi=100)
        
        np.random.seed(19680801)
        # create random data
        xdata = np.random.random([2, 50])        
        # split the data into two parts
        xdata1 = xdata[0, :]
        xdata2 = xdata[1, :]

        # sort the data so it makes clean curves
        xdata1.sort()
        xdata2.sort()

        # create some y data points
        ydata1 = xdata1 ** 2 
        ydata2 = 1 - xdata2 ** 3

        # Graphs plotted 
        sc.axes.plot(xdata1, ydata1, color ='tab:blue')
        sc.axes.plot(xdata2, ydata2, color ='tab:orange')

        # set the limits
        sc.axes.set_xlim([0, 1])
        sc.axes.set_ylim([0, 1])
        # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second.
        toolbar = NavigationToolbar(sc, self)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(toolbar)
        layout.addWidget(sc)
        # Create a placeholder widget to hold our toolbar and canvas.
        widget = QtWidgets.QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        self.show()
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
app.exec_()






















Код написан согласно документации PyQT5 && Matplotlib

Thursday, May 19, 2022

Command tee in bash on Linux

 boris@boris-All-Series:~/PYTHON/SWITCH$ cat switchCase10.py

def number_to_string(agrument):

    match agrument:

        case 0:

            return "zero"

        case 1:

            return "one"

        case 2:

            return "two"

        case default:

            return "something"

if __name__ == "__main__":

    agrument = 1

    print(number_to_string(agrument))

    agrument = 2

    print(number_to_string(agrument))

boris@boris-All-Series:~/PYTHON/SWITCH$ python3.10 switchCase10.py | tee logsw.txt

one

two

boris@boris-All-Series:~/PYTHON/SWITCH$ cat logsw.txt

one

two































Tuesday, May 17, 2022

Data Visualization in Python with matplotlib, Seaborn, and Bokeh

 Визуализация данных — важный аспект всех приложений ИИ и машинного обучения. Вы можете получить ключевое представление о своих данных с помощью различных графических представлений. В этом уроке мы поговорим о нескольких вариантах визуализации данных в Python. Мы будем использовать набор данных MNIST и библиотеку Tensorflow для обработки чисел и обработки данных. Чтобы проиллюстрировать различные методы создания различных типов графиков, мы будем использовать графические библиотеки Python, а именно matplotlib, Seaborn и Bokeh.

(.env) boris@boris-All-Series:~/PYTHON/SEABORN$ cat seabornPlottting1.py

from tensorflow.keras.datasets import mnist

from tensorflow import dtypes, tensordot

from tensorflow import convert_to_tensor, linalg, transpose

import numpy as np

import matplotlib.pyplot as plt

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

 

# Load dataset

(x_train, train_labels), (_, _) = mnist.load_data()

# Choose only the digits 0, 1, 2

total_classes = 3

ind = np.where(train_labels < total_classes)

x_train, train_labels = x_train[ind], train_labels[ind]

# Verify the shape of training data

total_examples, img_length, img_width = x_train.shape

print('Training data has ', total_examples, 'images')

print('Each image is of size ', img_length, 'x', img_width)

 

# Convert the dataset into a 2D array of shape 18623 x 784

x = convert_to_tensor(np.reshape(x_train, (x_train.shape[0], -1)),

                      dtype=dtypes.float32)

# Eigen-decomposition from a 784 x 784 matrix

eigenvalues, eigenvectors = linalg.eigh(tensordot(transpose(x), x, axes=1))

# Print the three largest eigenvalues

print('3 largest eigenvalues: ', eigenvalues[-3:])

# Project the data to eigenvectors

x_pca = tensordot(x, eigenvectors, axes=1)

 

# Create the plot

fig, ax = plt.subplots(figsize=(12, 8))

scatter = ax.scatter(x_pca[:, -1], x_pca[:, -2], c=train_labels, s=5)

legend_plt = ax.legend(*scatter.legend_elements(),

                       loc="lower left", title="Digits")

ax.add_artist(legend_plt)

plt.title('First Two Dimensions of Projected Data After Applying PCA')

plt.show()





























(.env) boris@boris-All-Series:~/PYTHON/SEABORN$ cat seabornPlottting2.py
from tensorflow.keras.datasets import mnist
from tensorflow.keras import utils
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Reshape
from tensorflow import dtypes, tensordot
from tensorflow import convert_to_tensor, linalg, transpose
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show
from bokeh.layouts import row
 
# Load dataset
(x_train, train_labels), (_, _) = mnist.load_data()
# Choose only the digits 0, 1, 2
total_classes = 3
ind = np.where(train_labels < total_classes)
x_train, train_labels = x_train[ind], train_labels[ind]
# Verify the shape of training data
total_examples, img_length, img_width = x_train.shape
print('Training data has ', total_examples, 'images')
print('Each image is of size ', img_length, 'x', img_width)
 
 
# Convert the dataset into a 2D array of shape 18623 x 784
x = convert_to_tensor(np.reshape(x_train, (x_train.shape[0], -1)),
                      dtype=dtypes.float32)
# Eigen-decomposition from a 784 x 784 matrix
eigenvalues, eigenvectors = linalg.eigh(tensordot(transpose(x), x, axes=1))
# Print the three largest eigenvalues
print('3 largest eigenvalues: ', eigenvalues[-3:])
# Project the data to eigenvectors
x_pca = tensordot(x, eigenvectors, axes=1)
 
 
# Prepare for classifier network
epochs = 10
y_train = utils.to_categorical(train_labels)
input_dim = img_length*img_width
# Create a Sequential model
model = Sequential()
# First layer for reshaping input images from 2D to 1D
model.add(Reshape((input_dim, ), input_shape=(img_length, img_width)))
# Dense layer of 8 neurons
model.add(Dense(8, activation='relu'))
# Output layer
model.add(Dense(total_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(x_train, y_train, validation_split=0.33, epochs=epochs, batch_size=10, verbose=0)
 
 
# Prepare pandas DataFrame
df_history = pd.DataFrame(history.history)
print(df_history)
 
 
# Create scatter plot in Bokeh
colormap = {0: "red", 1:"green", 2:"blue"}
my_scatter = figure(title="First Two Dimensions of Projected Data After Applying PCA",
                    x_axis_label="Dimension 1",
                    y_axis_label="Dimension 2",
                    width=500, height=400)
for digit in [0, 1, 2]:
    selection = x_pca[train_labels == digit]
    my_scatter.scatter(selection[:,-1].numpy(), selection[:,-2].numpy(),
                       color=colormap[digit], size=5, alpha=0.5,
                       legend_label="Digit "+str(digit))
my_scatter.legend.click_policy = "hide"
 
 
# Plot accuracy in Bokeh
p = figure(title="Training and validation accuracy",
           x_axis_label="Epochs", y_axis_label="Accuracy",
           width=500, height=400)
epochs_array = np.arange(epochs)
p.line(epochs_array, df_history['accuracy'], legend_label="Training",
       color="blue", line_width=2)
p.line(epochs_array, df_history['val_accuracy'], legend_label="Validation",
       color="green")
p.legend.click_policy = "hide"
p.legend.location = 'bottom_right'
 
show(row(my_scatter, p))


















REFERENCES

Sunday, May 15, 2022

How to select missing IDs in SQL (SQLite) Python

CREATE TABLE Persons (Personid INTEGER PRIMARY KEY AUTOINCREMENT, 

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int ); 

























































Wednesday, May 11, 2022

Parameter estimation using grid search with cross-validation

Производительность модели существенно зависит от значения гиперпараметров. Обратите внимание, что невозможно заранее узнать наилучшие значения гиперпараметров, поэтому в идеале нам нужно попробовать все возможные значения, чтобы узнать оптимальные значения. Выполнение этого вручную может занять значительное количество времени и ресурсов, поэтому мы используем GridSearchCV для автоматизации настройки гиперпараметров.

GridSearchCV — это функция, входящая в пакет model_selection Scikit-learn (или SK-learn). Поэтому важно отметить, что на компьютере должна быть установлена библиотека Scikit-learn. Эта функция помогает перебирать предопределенные гиперпараметры и подгонять вашу оценку (модель) к тренировочному набору. Итак, в итоге мы можем выбрать лучшие параметры из перечисленных гиперпараметров.

 В этом примере показано, как классификатор оптимизируется путем перекрестной проверки, которая выполняется с использованием объекта GridSearchCV в наборе для разработки, который содержит только половину доступных размеченных данных.

Производительность выбранных гиперпараметров и обученной модели затем измеряется на специальном оценочном наборе, который не использовался на этапе выбора модели.

(.env) [boris@Server35fedora GRIDCV]$ cat tuningGridSearchCV.py

"""

====================================

Parameter estimation using grid search with cross-validation

====================================

This examples shows how a classifier is optimized by cross-validation,which is done using the class:`~sklearn.model_selection.GridSearchCV` object on a development set that comprises only half of the available labeled data.The performance of the selected hyper-parameters and trained model is then measured on a dedicated evaluation set that was not used during the model selection step.

"""

from sklearn import datasets

from sklearn.model_selection import train_test_split

from sklearn.model_selection import GridSearchCV

from sklearn.metrics import classification_report

from sklearn.svm import SVC


# Loading the Digits dataset

digits = datasets.load_digits()


# To apply an classifier on this data, we need to flatten the image, to

# turn the data in a (samples, feature) matrix:

n_samples = len(digits.images)

X = digits.images.reshape((n_samples, -1))

y = digits.target


# Split the dataset in two equal parts

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)


# Set the parameters by cross-validation

tuned_parameters = [

    {"kernel": ["rbf"], "gamma": [1e-3, 1e-4], "C": [1, 10, 100, 1000]},

    {"kernel": ["linear"], "C": [1, 10, 100, 1000]},

]


scores = ["precision", "recall"]

for score in scores:

    print("# Tuning hyper-parameters for %s" % score)

    print()

    clf = GridSearchCV(SVC(), tuned_parameters, scoring="%s_macro" % score)

    clf.fit(X_train, y_train)

    print("Best parameters set found on development set:")

    print()

    print(clf.best_params_)

    print()

    print("Grid scores on development set:")

    print()

    means = clf.cv_results_["mean_test_score"]

    stds = clf.cv_results_["std_test_score"]

    for mean, std, params in zip(means, stds, clf.cv_results_["params"]):

        print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params))

    print()


    print("Detailed classification report:")

    print()

    print("The model is trained on the full development set.")

    print("The scores are computed on the full evaluation set.")

    print()

    y_true, y_pred = y_test, clf.predict(X_test)

    print(classification_report(y_true, y_pred))

    print()


(.env) [boris@Server35fedora GRIDCV]$ python tuningGridSearchCV.py
# Tuning hyper-parameters for precision

Best parameters set found on development set:

{'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}

Grid scores on development set:

0.986 (+/-0.016) for {'C': 1, 'gamma': 0.001, 'kernel': 'rbf'}
0.959 (+/-0.028) for {'C': 1, 'gamma': 0.0001, 'kernel': 'rbf'}
0.988 (+/-0.017) for {'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
0.982 (+/-0.026) for {'C': 10, 'gamma': 0.0001, 'kernel': 'rbf'}
0.988 (+/-0.017) for {'C': 100, 'gamma': 0.001, 'kernel': 'rbf'}
0.983 (+/-0.026) for {'C': 100, 'gamma': 0.0001, 'kernel': 'rbf'}
0.988 (+/-0.017) for {'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}
0.983 (+/-0.026) for {'C': 1000, 'gamma': 0.0001, 'kernel': 'rbf'}
0.974 (+/-0.012) for {'C': 1, 'kernel': 'linear'}
0.974 (+/-0.012) for {'C': 10, 'kernel': 'linear'}
0.974 (+/-0.012) for {'C': 100, 'kernel': 'linear'}
0.974 (+/-0.012) for {'C': 1000, 'kernel': 'linear'}

Detailed classification report:

The model is trained on the full development set.
The scores are computed on the full evaluation set.

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        89
           1       0.97      1.00      0.98        90
           2       0.99      0.98      0.98        92
           3       1.00      0.99      0.99        93
           4       1.00      1.00      1.00        76
           5       0.99      0.98      0.99       108
           6       0.99      1.00      0.99        89
           7       0.99      1.00      0.99        78
           8       1.00      0.98      0.99        92
           9       0.99      0.99      0.99        92

    accuracy                           0.99       899
   macro avg       0.99      0.99      0.99       899
weighted avg       0.99      0.99      0.99       899


# Tuning hyper-parameters for recall

Best parameters set found on development set:

{'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}

Grid scores on development set:

0.986 (+/-0.019) for {'C': 1, 'gamma': 0.001, 'kernel': 'rbf'}
0.957 (+/-0.028) for {'C': 1, 'gamma': 0.0001, 'kernel': 'rbf'}
0.987 (+/-0.019) for {'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
0.981 (+/-0.028) for {'C': 10, 'gamma': 0.0001, 'kernel': 'rbf'}
0.987 (+/-0.019) for {'C': 100, 'gamma': 0.001, 'kernel': 'rbf'}
0.982 (+/-0.026) for {'C': 100, 'gamma': 0.0001, 'kernel': 'rbf'}
0.987 (+/-0.019) for {'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}
0.982 (+/-0.026) for {'C': 1000, 'gamma': 0.0001, 'kernel': 'rbf'}
0.971 (+/-0.010) for {'C': 1, 'kernel': 'linear'}
0.971 (+/-0.010) for {'C': 10, 'kernel': 'linear'}
0.971 (+/-0.010) for {'C': 100, 'kernel': 'linear'}
0.971 (+/-0.010) for {'C': 1000, 'kernel': 'linear'}

Detailed classification report:

The model is trained on the full development set.
The scores are computed on the full evaluation set.

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        89
           1       0.97      1.00      0.98        90
           2       0.99      0.98      0.98        92
           3       1.00      0.99      0.99        93
           4       1.00      1.00      1.00        76
           5       0.99      0.98      0.99       108
           6       0.99      1.00      0.99        89
           7       0.99      1.00      0.99        78
           8       1.00      0.98      0.99        92
           9       0.99      0.99      0.99        92

    accuracy                           0.99       899
   macro avg       0.99      0.99      0.99       899
weighted avg       0.99      0.99      0.99       899

***************************************************
Пример использования класса GridSearchCV sklearn, чтобы узнать лучшие параметры модели AdaBoostRegressor для набора данных о ценах на жилье в Бостоне (Python) .
***************************************************
(.env) [boris@Server35fedora GRIDCV]$ cat AdaBoostRegressor.py
from sklearn.datasets import load_boston
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostRegressor
from sklearn.metrics import mean_squared_error, make_scorer, r2_score
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

boston = load_boston()
x, y = boston.data, boston.target
xtrain, xtest, ytrain, ytest=train_test_split(x, y, test_size=0.15)

abreg = AdaBoostRegressor()
params = {
 'n_estimators': [50, 100],
 'learning_rate' : [0.01, 0.05, 0.1, 0.5],
 'loss' : ['linear', 'square', 'exponential']
 }

score = make_scorer(mean_squared_error)

gridsearch = GridSearchCV(abreg, params, cv=5, return_train_score=True)
gridsearch.fit(xtrain, ytrain)
print(gridsearch.best_params_)

best_estim=gridsearch.best_estimator_
print(best_estim)

best_estim.fit(xtrain,ytrain)

ytr_pred=best_estim.predict(xtrain)
mse = mean_squared_error(ytr_pred,ytrain)
r2 = r2_score(ytr_pred,ytrain)
print("MSE: %.2f" % mse)
print("R2: %.2f" % r2)

ypred=best_estim.predict(xtest)
mse = mean_squared_error(ytest, ypred)
r2 = r2_score(ytest, ypred)
print("MSE: %.2f" % mse)
print("R2: %.2f" % r2)

x_ax = range(len(ytest))
plt.scatter(x_ax, ytest, s=5, color="blue", label="original")
plt.plot(x_ax, ypred, lw=0.8, color="red", label="predicted")
plt.legend()
plt.show()












































REFERECES