Baseestimator sklearn что это
Перейти к содержимому

Baseestimator sklearn что это

  • автор:

Быстрый старт ¶

Цель этого руководства — проиллюстрировать некоторые из основных функций, которые предоставляет scikit-learn . Он предполагает очень базовые практические знания методов машинного обучения (подбор модели, прогнозирование, перекрестная проверка и т. д.). Пожалуйста, обратитесь к инструкциям по установке для установки scikit-learn .

Scikit-learn — это библиотека машинного обучения с открытым исходным кодом, которая поддерживает обучение с учителем и без учителя. Библиотека также предоставляет различные инструменты для подбора модели, предварительной обработки данных, выбора модели, оценки модели и многие другие утилиты.

Обучение и предсказание: основы оценки

Scikit-learn предоставляет десятки встроенных алгоритмов и моделей машинного обучения, называемых оценщиками (extimators) . Каждая оценка может быть приспособлена к некоторым данным, используя свой метод подбора.

Вот простой пример, где мы обучаем RandomForestClassifier по некоторым очень простым данным:

>>> from sklearn.ensemble import RandomForestClassifier >>> clf = RandomForestClassifier(random_state=0) >>> X = [[ 1, 2, 3], # 2 записи (samples), 3 признака (features) . [11, 12, 13]] >>> y = [0, 1] # класс для каждой записи (для первой записи 0, для второй 1) >>> clf.fit(X, y) # обучение RandomForestClassifier(random_state=0)

Метод обучения (fit) обычно принимает 2 параметра:

  • Матрица признаков X . Размер X обычно равен (n_samples, n_features ), что означает, что выборки представлены в виде строк, а объекты представлены в виде столбцов.
  • Целевые значения y, которые являются действительными числами для задач регрессии или целыми числами для классификации (или любым другим дискретным набором значений). Для задач обучения без учителя указывать не нужно. y обычно представляет собой одномерный массив, где i -ый элемент соответствует целевому значению i -ой записи (строки) X .

Преобразователи и препроцессоры

Рабочие процессы машинного обучения часто состоят из разных частей. Типичный конвейер (pipeline) состоит из шага предварительной обработки, который преобразует или меняет данные, и конечного предиктора, который предсказывает целевые значения.

В scikit-learn , препроцессоры и преобразователи (transformers) следуют тому же API, что и объекты оценки (фактически все они наследуются от одного и того же BaseEstimator класса). Объекты-преобразователи не имеют метода прогнозирования , а имеют метод преобразования , который выводит недавно преобразованную матрицу выборки X :

>>> from sklearn.preprocessing import StandardScaler >>> X = [[0, 15], . [1, -10]] >>> # scale data according to computed scaling values >>> StandardScaler().fit(X).transform(X) array([[-1., 1.], [ 1., -1.]])

Так же вы можете применить разные преобразования к разным функциям: ColumnTransformer предназначен для этих случаев использования.

Конвейеры: связывание препроцессоров и оценщиков

Преобразователи и оценщики (предикторы) могут быть объединены в единый объединяющий объект: Pipeline . Конвейер предлагает тот же API, что и обычный оценщик: его можно настроить и использовать для прогнозирования с помощью fit и predict . Как мы увидим позже, использование конвейера также предотвратит утечку данных, то есть раскрытие некоторых данных тестирования в ваших обучающих данных.

В следующем примере мы загружаем набор данных Iris , разделяем его на обучающие и тестовые выборки и вычисляем показатель точности конвейера на тестовых данных:

>>> from sklearn.preprocessing import StandardScaler >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.pipeline import make_pipeline >>> from sklearn.datasets import load_iris >>> from sklearn.model_selection import train_test_split >>> from sklearn.metrics import accuracy_score . >>> # создание конвеера (pipeline) >>> pipe = make_pipeline( . StandardScaler(), . LogisticRegression() . ) . >>> # загрузка датасета Ирис и разделение на тестовю и обучающую выборку >>> X, y = load_iris(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) . >>> # обучение с использованием пайплайна >>> pipe.fit(X_train, y_train) Pipeline(steps=[('standardscaler', StandardScaler()), ('logisticregression', LogisticRegression())]) >>> # проверяем оценку с помощью accuracy_score оценки на тестовых данных >>> accuracy_score(pipe.predict(X_test), y_test) 0.97.

Оценка модели

Обучение модели по некоторым данным не означает, что она будет хорошо предсказывать на неизвестных ранее данные. Это нужно оценивать напрямую. Мы только что видели вспомогательный метод train_test_split , который разбивает набор данных на наборы для обучения и тестирования, но scikit-learn предоставляет множество других инструментов для оценки модели, в частности, для перекрестной проверки.

Здесь мы кратко покажем, как выполнить 5-кратную процедуру перекрестной проверки с помощью метода cross_validate . Обратите внимание, что также можно вручную перебирать части данных (фолды — folds), использовать различные стратегии разделения данных и использовать пользовательские функции оценки. Пожалуйста, обратитесь к нашему Руководству пользователя для более подробной информации:

>>> from sklearn.datasets import make_regression >>> from sklearn.linear_model import LinearRegression >>> from sklearn.model_selection import cross_validate . >>> X, y = make_regression(n_samples=1000, random_state=0) >>> lr = LinearRegression() . >>> result = cross_validate(lr, X, y) # по умолчанию разбивается на 5 фолдов >>> result['test_score'] # оценка r-квадрат array([1., 1., 1., 1., 1.])

Автоматический подбор параметров

Все оценщики имеют параметры (часто называемые в литературе гиперпараметрами), которые можно настраивать. Обобщающая способность оценщика часто критически зависит от нескольких параметров. Например, RandomForestRegressor имеет n_estimators параметр, определяющий количество деревьев в лесу, и параметр max_depth , определяющий максимальную глубину каждого дерева. Довольно часто неясно, какими должны быть точные значения этих параметров, поскольку они зависят от имеющихся данных.

Scikit-learn предоставляет инструменты для автоматического поиска наилучших комбинаций параметров (через перекрестную проверку). В следующем примере мы случайным образом ищем наилучшие параметры среди множества различных параметров случайного леса RandomizedSearchCV . Когда поиск завершен, RandomizedSearchCV ведет себя так, как если бы RandomForestRegressor был подобран с лучшим набором параметров. Подробнее читайте в руководстве пользователя:

>>> from sklearn.datasets import fetch_california_housing >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.model_selection import RandomizedSearchCV >>> from sklearn.model_selection import train_test_split >>> from scipy.stats import randint . >>> X, y = fetch_california_housing(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) . >>> # указывает набор параметров, которые будут использованы >>> param_distributions = . >>> # создание search объекта, и обучение на тренировочных данных >>> search = RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0), . n_iter=5, . param_distributions=param_distributions, . random_state=0) >>> search.fit(X_train, y_train) RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0), n_iter=5, param_distributions=, random_state=0) >>> search.best_params_ >>> # наилучшие параметры оказались - max_depth=9 and n_estimators=4 >>> search.score(X_test, y_test) 0.73.

На практике почти всегда нужно искать по набору параметров , а не по одному параметру. Одна из основных причин заключается в том, что если вы примените шаг предварительной обработки ко всему набору данных без использования конвейера, а затем выполните какую-либо перекрестную проверку, вы нарушите фундаментальное предположение о независимости между данными обучения и тестирования. Поскольку вы предварительно обработали данные, используя весь набор данных, некоторая информация о тестовых наборах доступна для обучающих наборов. Это приведет к переоценке обобщающей способности оценщика (подробнее вы можете прочитать в этом посте на Kaggle ).

Использование конвейера для перекрестной проверки и поиска в значительной степени убережет вас от этой распространенной ловушки.

Следующие шаги

Мы кратко рассмотрели настройку и прогнозирование оценщиков, этапы предварительной обработки, конвейеры, инструменты перекрестной проверки и автоматический поиск гиперпараметров. Это руководство должно дать вам обзор некоторых основных функций библиотеки.

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

Вы также можете ознакомиться с нашими многочисленными примерами , иллюстрирующими использование scikit-learn в различных контекстах.

Если вы хотите помочь проекту с переводом, то можно обращаться по следующему адресу support@scikit-learn.ru
© 2007 — 2020, scikit-learn developers (BSD License).

Exploring the Role of Base Estimators in Machine Learning Algorithms

Exploring the Role of Base Estimators in Machine Learning Algorithms

sklearn.base.BaseEstimator is a base class in the scikit-learn machine learning library that defines the basic interface for all estimators in scikit-learn. It provides a set of methods and attributes that any custom estimator needs to implement or inherit to work properly with the scikit-learn framework. In this explanation, we will cover the different methods and attributes of BaseEstimator in detail.

No alt text provided for this image

Estimators

In machine learning, an estimator is a tool that learns from data to make predictions or classify new instances. Scikit-learn provides a variety of pre-built estimators that can be used out-of-the-box, but it also allows users to define their own custom estimators. The BaseEstimator class provides a basic template that can be used as a starting point for creating new estimators.

Attributes

An estimator in scikit-learn is expected to have certain attributes that provide information about its state or configuration. The following attributes are defined in the BaseEstimator class:

No alt text provided for this image

  • estimator_type —The estimator_type attribute is a string that identifies the type of estimator. This can be used to differentiate between different types of estimators, such as classifiers, regressors, or transformers.
  • named_transformers_ -The named_transformers_ attribute is a dictionary that maps string names to transformer objects. This is used in the Pipeline and ColumnTransformer classes to specify the names and order of transformers.
  • classes_ —The classes_ attribute is a list or array that contains the unique class labels for a classifier. This is used in classification tasks to specify the possible output classes that the estimator can predict.
  • n_features_in_ -The n_features_in_ attribute is an integer that specifies the number of input features that the estimator expects. This is used in transformers to check that the input data has the correct number of features.

Methods

The BaseEstimator class also defines several methods that need to be implemented or overridden in custom estimators. These methods provide a consistent interface for all estimators in scikit-learn.

No alt text provided for this image

  • get_params() -The get_params() method returns a dictionary of the estimator’s parameters and their values. This is used to get the current configuration of the estimator, which can be used to recreate the estimator with the same parameters.
  • set_params() —The set_params() method takes a dictionary of parameter values and sets the corresponding attributes of the estimator. This is used to change the configuration of the estimator after it has been created.
  • fit() -The fit() method takes a set of training data and fits the estimator to the data. This is where the estimator learns from the data and adjusts its parameters to make predictions.
  • predict() -The predict() method takes a set of input data and returns the predicted output values. This is used for both classification and regression tasks.
  • predict_proba() —The predict_proba() method takes a set of input data and returns the predicted probability values for each possible output class. This is used for classification tasks to obtain a probability distribution over the output classes.
  • score() -The score() method takes a set of input and output data and returns a score that represents the quality of the estimator’s predictions. This is used to evaluate the performance of the estimator.
  • transform() —The transform() method takes a set of input data and returns a transformed version of the data. This is used by transformers to preprocess the input data before it is fed to an estimator.
  • inverse_transform() —The inverse_transform() method takes a set of transformed data and returns the original input data. This is used by transformers to convert.

Here’s an example of a custom estimator that inherits from BaseEstimator

from sklearn.base import BaseEstimator: class MyEstimator(BaseEstimator): def __init__(self, param1=1, param2=2): self.param1 = param1 self.param2 = param2 def fit(self, X, y=None): # Fit the estimator to the data # This method should return self return self def predict(self, X): # Make predictions for the input data # This method should return a numpy array of predicted output values return y_pred

In this example, MyEstimator is a simple estimator that takes two parameters param1 and param2, and implements the fit() and predict() methods. The fit() method takes input data X and optional output data y, and returns the fitted estimator. The predict() method takes input data X and returns a numpy array of predicted output values. Note that we did not implement all the methods and attributes of BaseEstimator in this example, but we could add them if needed for our specific use case.

We can use this custom estimator in the same way as any other estimator in scikit-learn, for example:

from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # Load the iris dataset data = load_iris() X, y = data.data, data.target # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Create an instance of MyEstimator with default parameters estimator = MyEstimator() # Fit the estimator to the training data estimator.fit(X_train, y_train) # Make predictions on the test data y_pred = estimator.predict(X_test) # Evaluate the performance of the estimator accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: ")

In this example, we load the iris dataset, split it into training and test sets, create an instance of MyEstimator, fit it to the training data, make predictions on the test data, and evaluate its performance using accuracy score. Note that we did not define the predict_proba() method in MyEstimator, so we cannot use it in this example. If we need this method for our use case, we can add it to MyEstimator by implementing the required logic.For more detail and brief explanation check our original article on-base.BaseEstimator

No alt text provided for this image

Conclusion

In machine learning, a base estimator is a simple model or algorithm used as a building block for more complex models. The choice of a base estimator depends on the specific problem being solved and the characteristics of the data.

There are many types of base estimators, including linear regression, decision trees, support vector machines, and k-nearest neighbors. Each type of estimator has its own strengths and weaknesses and may be more or less appropriate depending on the particular problem and data set.

The performance of the overall model depends heavily on the choice of the base estimator, as well as other factors such as the number of estimators used and the hyperparameters chosen.

In summary, base estimators are a critical component of many machine learning algorithms and the choice of an appropriate base estimator can have a significant impact on the performance of the overall model. It is important to carefully consider the characteristics of the data and the problem is solved when selecting a base estimator.

Thank you for taking the time to read this article. We hope you found it informative and helpful. If you have any doubts or questions about the content, please don’t hesitate to ask in the comments below. Your feedback is always appreciated and helps us improve the quality of our writing. Once again, thank you for your time and attention. we look forward to hearing from you!

Создание пользовательских преобразователей данных

Рассмотрим, как готовить собственные преобразователи данных (трансформеры) так, чтобы они поддерживались механизмами последовательной обработки, реализованными в библиотеке Scikit-learn. Для демонстрации работы создадим обучающие датафреймы:

import pandas as pd df_train = pd.DataFrame([['fourth_cat1', 'third_cat2', 1], ['first_cat1', 'third_cat2', 1], ['second_cat1', 'third_cat2', 2], ['second_cat1', 'second_cat2', 5]]) df_valid = pd.DataFrame([['fifth_cat1', 'third_cat2'], ['second_cat1', 'third_cat2'], ['second_cat1', 'second_cat2']])

Использование трансформатора предполагает его обучение методом fit и запуск методом transform. Они охватывают основной функционал преобразователя и требуют самостоятельной реализации. Такие имена методов нужны для поддержки в инструментах sklearn. Кроме того, для этих же целей реализуйте трансформаторы в виде классов, наследующих TransformerMixin и BaseEstimator из sklearn.base. Это откроет новому классу автоматический доступ к методам fit_transform, get_param, set_param, необходимым для поддержки в пайплайнах, функциях подбора гиперпараметров. Для примера создадим трансформатор преобразования значений категориальных колонок датасета в среднее значение по целевой переменной:

from sklearn.base import TransformerMixin, BaseEstimator class MeanEncoding(TransformerMixin, BaseEstimator): mean_d = <> def __init__(self, unknown_val = 0): self.unknown_val = unknown_val def fit(self, X, y): for col in X.select_dtypes(include=['category', 'object']).columns: self.mean_d[col] = y.groupby(X[col]).mean().to_dict() return self def transform(self, X): X_tr = X.copy() for col in X_tr.select_dtypes(include=['category', 'object']).columns: X_tr[col] = X_tr[col].map(lambda x: self.mean_d[col].get(x, self.unknown_val)) return X_tr

Обучим и применим новый класс к тренировочной выборке:

enc = MeanEncoding(unknown_val=-5) enc.fit_transform(df_train.drop(columns=2), df_train[2])

Выведем созданный словарь для хранения значений категорий и применим класс к валидационной выборке:

enc.mean_d enc.transform(df_valid)

Так как мы соблюли правила создания трансформера, его можно встраивать в пайплайны:

from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler tr = Pipeline(steps=[('mean', MeanEncoding()),('sc', MinMaxScaler())]) tr.fit_transform(df_train.drop(columns=2),df_train[2])

и применим пайплайн к валидационному набору:

tr.transform(df_valid)

Не пропустите ничего интересного и подписывайтесь на страницы канала в других социальных сетях:

sklearn.base.BaseEstimator

Все оценщики должны указывать все параметры, которые могут быть установлены на уровне класса в их __init__ , как явные аргументы ключевого слова (не *args или **kwargs ).

Methods

Получите параметры для этого средства оценки.

Установите параметры этого средства оценки.

get_params(deep=True)[source]

Получите параметры для этого средства оценки.

Parameters: deepbool, default=True

Если True, будут возвращены параметры для этого оценщика и содержащиеся подобъекты, которые являются оценщиками.

Returns: paramsdict

Имена параметров сопоставлены с их значениями.

Установите параметры этого средства оценки.

Метод работает как с простыми оценщиками, так и с вложенными объектами (такими как Pipeline ). Последние имеют параметры form __ , чтобы можно было обновлять каждый компонент вложенного объекта.

Parameters: **paramsdict

Returns: selfestimator instance

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *