Git Product home page Git Product logo

aimclub / fedot Goto Github PK

View Code? Open in Web Editor NEW
606.0 11.0 83.0 228.29 MB

Automated modeling and machine learning framework FEDOT

Home Page: https://fedot.readthedocs.io

License: BSD 3-Clause "New" or "Revised" License

Python 99.93% Dockerfile 0.07% Shell 0.01%
automl machine-learning evolutionary-algorithms genetic-programming structural-learning automated-machine-learning hyperparameter-optimization parameter-tuning automation multimodality

fedot's Introduction

Logo of FEDOT framework

package
Supported Python Versions Supported Python Versions
tests
Build Status Integration Build Status Coverage Status
docs Documentation Status
license
Supported Python Versions
stats
downloads_stats
support
Telegram Chat
languages
eng rus
mirror
GitLab mirror for this repository
funding
Acknowledgement to ITMO Acknowledgement to NCCR

FEDOT is an open-source framework for automated modeling and machine learning (AutoML) problems. This framework is distributed under the 3-Clause BSD license.

It provides automatic generative design of machine learning pipelines for various real-world problems. The core of FEDOT is based on an evolutionary approach and supports classification (binary and multiclass), regression, clustering, and time series prediction problems.

The structure of the AutoML workflow in FEDOT

The key feature of the framework is the complex management of interactions between various blocks of pipelines. It is represented as a graph that defines connections between data preprocessing and model blocks.

The project is maintained by the research team of the Natural Systems Simulation Lab, which is a part of the National Center for Cognitive Research of ITMO University.

More details about FEDOT are available in the next video:

Introducing Fedot

FEDOT concepts

Installation

  • Package installer for Python pip

The simplest way to install FEDOT is using pip:

$ pip install fedot

Installation with optional dependencies for image and text processing, and for DNNs:

$ pip install fedot[extra]
  • Docker container

Available docker images can be found here here.

How to Use

FEDOT provides a high-level API that allows you to use its capabilities in a simple way. The API can be used for classification, regression, and time series forecasting problems.

To use the API, follow these steps:

  1. Import Fedot class
from fedot.api.main import Fedot
  1. Initialize the Fedot object and define the type of modeling problem. It provides a fit/predict interface:
  • Fedot.fit() begins the optimization and returns the resulting composite pipeline;
  • Fedot.predict() predicts target values for the given input data using an already fitted pipeline;
  • Fedot.get_metrics() estimates the quality of predictions using selected metrics.

NumPy arrays, Pandas DataFrames, and the file's path can be used as sources of input data. In the case below, x_train, y_train and x_test are numpy.ndarray():

model = Fedot(problem='classification', timeout=5, preset='best_quality', n_jobs=-1)
model.fit(features=x_train, target=y_train)
prediction = model.predict(features=x_test)
metrics = model.get_metrics(target=y_test)

More information about the API is available in the documentation section and advanced approaches are in the advanced section.

Examples & Tutorials

Jupyter notebooks with tutorials are located in examples repository. There you can find the following guides:

Notebooks are issued with the corresponding release versions (the default version is 'latest').

Also, external examples are available:

Extended examples:

Also, several video tutorials are available available (in Russian).

Publications About FEDOT

We also published several posts devoted to different aspects of the framework:

In English:

In Russian:

  • Как AutoML помогает создавать модели композитного ИИ — говорим о структурном обучении и фреймворке FEDOT - habr.com
  • Прогнозирование временных рядов с помощью AutoML - habr.com
  • Как мы “повернули реки вспять” на Emergency DataHack 2021, объединив гидрологию и AutoML - habr.com
  • Чистый AutoML для “грязных” данных: как и зачем автоматизировать предобработку таблиц в машинном обучении - ODS blog
  • Фреймворк автоматического машинного обучения FEDOT (Конференция Highload++ 2022) - presentation
  • Про настройку гиперпараметров ансамблей моделей машинного обучения - habr.com

In Chinese:

  • 生成式自动机器学习系统 (presentation at the "Open Innovations 2.0" conference) - youtube.com

Project Structure

The latest stable release of FEDOT is in the master branch.

The repository includes the following directories:

  • Package core contains the main classes and scripts. It is the core of the FEDOT framework
  • Package examples includes several how-to-use-cases where you can start to discover how FEDOT works
  • All unit and integration tests can be observed in the test directory
  • The sources of the documentation are in the docs directory

Current R&D and future plans

Currently, we are working on new features and trying to improve the performance and the user experience of FEDOT. The major ongoing tasks and plans:

  • Implementation of meta-learning based at GNN and RL (see MetaFEDOT)
  • Improvement of the optimisation-related algorithms implemented in GOLEM.
  • Support for more complicated pipeline design patters, especially for time series forecasting.

Any contribution is welcome. Our R&D team is open for cooperation with other scientific teams as well as with industrial partners.

Documentation

Also, a detailed FEDOT API description is available in Read the Docs.

Contribution Guide

  • The contribution guide is available in this repository.

Acknowledgments

We acknowledge the contributors for their important impact and the participants of numerous scientific conferences and workshops for their valuable advice and suggestions.

Side Projects

  • The optimisation core implemented in GOLEM repository.
  • The prototype of the web-GUI for FEDOT is available in the FEDOT.WEB repository.
  • The prototype of FEDOT-based meta-AutoML in the MetaFEDOT repository.

Contacts

Supported by

Citation

@article{nikitin2021automated,

title = {Automated evolutionary approach for the design of composite machine learning pipelines}, author = {Nikolay O. Nikitin and Pavel Vychuzhanin and Mikhail Sarafanov and Iana S. Polonskaia and Ilia Revin and Irina V. Barabanova and Gleb Maximov and Anna V. Kalyuzhnaya and Alexander Boukhanovsky}, journal = {Future Generation Computer Systems}, year = {2021}, issn = {0167-739X}, doi = {https://doi.org/10.1016/j.future.2021.08.022}}

@inproceedings{polonskaia2021multi,

title={Multi-Objective Evolutionary Design of Composite Data-Driven Models}, author={Polonskaia, Iana S. and Nikitin, Nikolay O. and Revin, Ilia and Vychuzhanin, Pavel and Kalyuzhnaya, Anna V.}, booktitle={2021 IEEE Congress on Evolutionary Computation (CEC)}, year={2021}, pages={926-933}, doi={10.1109/CEC45853.2021.9504773}}

Other papers - in ResearchGate.

fedot's People

Contributors

andreygetmanov avatar apovidlo avatar barabanovairina avatar chrislisbon avatar denissidoren avatar dependabot[bot] avatar dreamlone avatar drmpn avatar elishaflacon avatar gkirgizov avatar glad4enkonm avatar gorokhovnik avatar grigorijasnovidov avatar iiakyjiuh avatar itay-raveh avatar j3fall avatar kasyanovse avatar lopa10ko avatar magleb avatar maypink avatar morrisnein avatar nicl-nno avatar nunkyl avatar sash0check avatar technocreep avatar trellixvulnteam avatar v1docq avatar valer1435 avatar yamlyubov avatar yanapolonskaya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fedot's Issues

Реализовать для скорингового примера реализацию с помощью других фреймворков: TPOT, H2O, AutoSKlearn etc.

  1. Применить для scoring example несколько AutoML фреймворков (файлы для скорингового примера лучше брать из ветки refactor-evo-strategy.
  2. Попробовать вывести информацию о отобранных признаках, виде модели и её настройках, которые получаются в ходе оптимизации.
  3. Сохранить полученную в ходе оптимизации модель для быстрого воспроизведения результата.

Тест на корректное разделение train и test (имитация переобучения)

Нужно сгенерить несколько датасетов, на которых можно выявить,

  1. не пытается ли модель обучаться на test и valid части
  2. не переобучается ли она на любых доступных train-данных

В датасетах можно делать разные комбинации:

  1. корректный train, случайный test
  2. случайные train и test
  3. случайный train, корректный test
    и аналогичный комбинации с valid-выборкой (как в скоринговом примере)

Скорее всего, сейчас эти тесты будут падать.

Реализовать передачу макс. времени выполнения в композер и его учёт

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

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

Пример реализации можно посмотреть в tpot(код связанный с EpistasisLab/tpot#723)

Сделать mock-дерева типов для теста ModelTypesRepository

Нужно реализовать mock для ModelTypesRepository в этом и остальных тестов в этом скрипте.

Сейчас у репозитория в конструкторе создается и инициализируется поле "дерево" - self._tree.
Для удобства в тесте нужно сделать mock на это поле, чтобы не было дублирования (как сейчас)

Провести ревизию композеров

  • Взять улучшенную реализацию случайного композера из composer-experiments
  • Сравнить функции генерации случайных деревьев из composer-experiments и chain-regularisation/master.
    (см #80 (comment))

Бенчмарки для композера: качество, робастность, сходимость.

  1. Реализовать генерацию случайных синтетических датасетов.
  2. Обучить на них набор моделей.
  3. Сформировать на их основе случайные цепочки произвольной структуры.
  4. Ввести метрики качества для таких тестов (качество, робастность, сходимость etc)
  5. Выполнить тесты по оценке эффективности для существующего ГП-композера (насколько "хорошо" восстановливается структра дерева).

Реализовать выполнение цепочки моделей

Взять несколько простых моделей (например, лин. регресссий), вручную создать цепочку нод и реализовать "раскручивание" моделей при вызове последней из них.

Т.е. математически что-то вроде этого должно получиться:

y = a1(a2(a3*x+b3)+b2)+b1

Расширенное описание:

Сейчас у нас есть модели в отдельных нодах и их можно выполнять (как это сделано, например, в тесте test_eval_strategy_logreg)

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

Тогда при вывозе метода apply в последней в цепочке ноде должны выполняться все предшествующие её ноды , и только потом - вызванная.

image

image

Где a и b - коэфициенты линейных регрессионных моделей

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

Данные можно взять любые, не обязательно получившаяся модель должна быть эффективной - главное, чтобы при вывозе apply в ноде 4 выполнялся подсчет в node1, node2, node3, потом обучалась и выполнялась модель в node 4.

Ну и учитывать что уровней такой иерархии может быть больше двух.

Реализовать прикладной пример по прогнозированию SSH с помощью LSTM

Что нужно сделать:
0) Подготовать данные SSH, которые использовались в
https://niuitmo-my.sharepoint.com/:w:/g/personal/240590_niuitmo_ru/EdtbfZ7BHclCuzz1sg0yN2MBDN23F08KbVT3lAau6EgKGg?e=UgPVGo

  1. Добавить твою реализацию LSTM в evaluation.py (и соответсвующие enum-ы - см. существующие модели). Инструкция есть тут:
    https://github.com/ITMO-NSS-team/FEDOT.Algs/wiki/How-to-embed-custom-model-into-the-Fedot-pipeline

  2. Попробовать запустить прогнозирование по аналогии с ARIMA в metocean_forecasting_problem.py
    [тут нужно добавить регрессионные модели и оператор разности между рядами, сделаю сам]

  3. Запустить итоговый модельный сетап.

Если LSTM обучается долго - возможно есть смысл сохранять обученную модель на диск.

Починить интеграцию с coveralls

Сейчас процент покрытия отображается некорректно (84% было месяца 3 назад, кажется).
Надо разобраться, почему coveralls не обновляет эти значения.
Это можно исправить уже после переноса репозитория в ITMO.NSS_Team ближе к публичному релизу.
image

Реализовать базовый класс для Chain в рамках композера

Описание предлагаемой реализации:

В FEDOT.Algs мы реализуем именно алгоритмы оптимизации деревьев (символьных, gp, ast - можем как угодно их называть. Соответственно, для удобства нужен интерфейс типа GPTree (в котором есть все нужные методы для работы с узлами).

В ядре остается композеры и его реализации, в частности, GPComposer. Их единственная ответственность - композировать цепочки(copose_chain).

Внутри GPComposer::compose_chain импортируется GPOptimizer. Для того, чтобы его использовать, мы сначала конвертируем Chain в GPTree, и оптимизируем его. Результат конвертируется обратно в Chain. В Jav-е есть идеально подходящая штука для таких вещей - анонимные классы. Т.е. мы могли бы объявить анонимный класс, в котором реализовать методы класса GPTree: add_node, root_node и т.д. (частично делегируя вызовы методов GPTree
методам Chain). В питоне, к сожалению, я знаю, как это сделать дешево и по аналогии.
Да, при таком подходе ядро явно завязывается на FEDOT.Algs, но, имхо, это нормально, т.к. алгоритмы сами по себе - вещь более абстрактная, чем сборка цепочек из моделей ML. Зато сами алгоритмы оптимизации цепочек теперь можно использовать, совершенно не привязываясь к композеру и т.д.

image

Доработать визуализацию деревьев

Сейчас в https://github.com/nccr-itmo/FEDOT/blob/master/core/composer/visualisation.py есть вариант с помощью networkx, но он:

  1. требует громоздкой установки graphviz (https://itmo-nss-team.github.io/FEDOT.Docs/fedot/quick-start)
  2. дает не слишком красивые и гибкие визуализации
  3. недостаточно информативен (не выводятся гиперпараметры моделей).

Необходимо вместо него реализовать нативный вариантат отрисовки.

Вот тут есть оч. старая реализация кастомной отрисовки моделей, но это совсем примитивный вариант.
https://github.com/nccr-itmo/FEDOT/blob/custom_visualise/core/composer/tree_drawing.py

Модифицировать композер, обеспечив сохранность уже обученных нод

Сейчас при каждом составлении цепочки все ноды пересоздаются и поэтому обучаются заново (кэш теряется).

Из-за этого на композирование уходит много времени. Нужно реализовать preserving нод, которые не затронуты мутацией или кроссовером.

Technical debt and refactoring

Доработки и рефакторинг после показа:

  1. Отрицательные значения метрик (см. ROC AUC): добавить property для метрик, которые передаются алгоритму оптимизации.
  2. Хранение reference_data в chain - тут нужно подумать.
  3. Обработка Nan-ов в EvaluationStrategy.
  4. Дублирование кода в models. Возможно, добавить прослойку для SKLearn/ML Model.
  5. TBA

Реализовать регуляризацию цепочек в ходе композирования

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

Это можно попробовать исправить вот так: в отличие от большинства задач ГП, у нас дорогой является лишь задача обучения модели. Сделать предсказание относительно дешево.

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

Реализовать метод самовалидации цепочки

Проверки для chain на :

  • отсутствие циклов
  • отсутствие изолированных нод и подграфов
  • отсутствие нескольких корневых нод
  • отсутствие нод, ссылающихся сами на себя
  • наличие primary-нод
  • другие проверки, если таковые можно придумать

Можно вызывать такой метод каждый раз при добавлении ноды в chain.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.