Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API improvements #990

Merged
merged 15 commits into from
Jan 30, 2023
Merged

API improvements #990

merged 15 commits into from
Jan 30, 2023

Conversation

MorrisNein
Copy link
Collaborator

@MorrisNein MorrisNein commented Nov 21, 2022

Closes #906, #873, #874.

Change list:

  • Allowed Fedot.fit to get path to features and target via Path objects.

  • Wrote explicit docstring for Fedot.fit.

  • Used generic type FeaturesType in Fedot.fit annotation.

  • Unified index column detection during CSV loading.

  • Fixed time series loading from numpy arrays.

@MorrisNein MorrisNein added in progress task in progress api Anything related to user-facing interfaces & parameter passing labels Nov 21, 2022
@MorrisNein MorrisNein self-assigned this Nov 21, 2022
@MorrisNein MorrisNein removed the in progress task in progress label Nov 22, 2022
@MorrisNein MorrisNein force-pushed the api_improvements branch 5 times, most recently from eb4cf57 to 343ce13 Compare November 25, 2022 14:33
fedot/core/data/data.py Outdated Show resolved Hide resolved
fedot/core/data/data.py Outdated Show resolved Hide resolved
Copy link
Collaborator

@andreygetmanov andreygetmanov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень здорово! Код стал лаконичнее и читабельнее.
Мне кажется, стоит обновить соответствующие тесты (добавить проверку на правильное определение колонок и пр.). Они лежат в test_data.py, например

fedot/api/api_utils/data_definition.py Outdated Show resolved Hide resolved
fedot/api/main.py Outdated Show resolved Hide resolved
fedot/core/data/data.py Outdated Show resolved Hide resolved
fedot/core/data/data.py Outdated Show resolved Hide resolved
test/unit/api/test_main_api.py Show resolved Hide resolved
@MorrisNein MorrisNein force-pushed the api_improvements branch 3 times, most recently from 8406523 to 51f93bd Compare December 26, 2022 14:33
@MorrisNein MorrisNein force-pushed the api_improvements branch 2 times, most recently from 8b1ec5c to 51d0950 Compare January 26, 2023 15:49
@MorrisNein
Copy link
Collaborator Author

MorrisNein commented Jan 26, 2023

@andreygetmanov, добавил тесты для определения индексных колонок

51d0950

@codecov
Copy link

codecov bot commented Jan 26, 2023

Codecov Report

Merging #990 (f489698) into master (cf11145) will increase coverage by 0.26%.
The diff coverage is 93.54%.

@@            Coverage Diff             @@
##           master     #990      +/-   ##
==========================================
+ Coverage   87.54%   87.80%   +0.26%     
==========================================
  Files         208      208              
  Lines       13822    13962     +140     
==========================================
+ Hits        12100    12260     +160     
+ Misses       1722     1702      -20     
Impacted Files Coverage Δ
fedot/api/api_utils/api_data.py 87.50% <ø> (ø)
fedot/api/main.py 81.30% <ø> (ø)
fedot/core/repository/dataset_types.py 100.00% <ø> (ø)
fedot/core/data/multi_modal.py 85.29% <84.00%> (+0.91%) ⬆️
fedot/core/data/data.py 86.10% <96.22%> (-0.67%) ⬇️
fedot/api/api_utils/data_definition.py 86.07% <100.00%> (+0.74%) ⬆️
fedot/core/dag/graph_delegate.py 100.00% <0.00%> (ø)
fedot/core/pipelines/automl_wrappers.py 0.00% <0.00%> (ø)
fedot/core/optimisers/composer_requirements.py 100.00% <0.00%> (ø)
... and 59 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@gkirgizov gkirgizov mentioned this pull request Jan 28, 2023
4 tasks
fedot/core/data/data.py Show resolved Hide resolved
If ``None``, then check the first column's name and use it as index if succeeded
(see the param ``possible_idx_keywords``).\n
Set ``False`` to skip the check and rearrange a new integer index.
possible_idx_keywords: lowercase keys to find. If the first data column contains one of the keys,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не понимаю, а зачем нужен этот парамметр. В каких случаях пользователь будет его заполнять? Как мне кажется, он дублирует функциональность парамметра index_col.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынести во внешний API было идеей @nicl-nno. Основная задумка в том, что при загрузке нескольких файлов пользователь мог бы один раз указать, какие индексы в них используются.

Сейчас, спустя время, думается, что лучше бы пользователь самостоятельно указывал индекс для каждого конкретного файла, чтобы не перегружать внешний интерфейс. Логика параметра не выглядит явной для внешнего пользователя. @nicl-nno, что думаешь?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Смысл параметра был в том, что когда мы автоматизированно обрабатываем кучу разнородных файлов - то нам удобно указать набор возможных названий индекса. Наверное, можно это объединить с index_col, но давайте уже в следующих PR про это подумает.

columns_to_drop: Optional[List[Union[str, int]]] = None,
columns_to_use: Optional[List[Union[str, int]]] = None):

def define_index_column(candidate_columns: List[str]) -> Optional[str]:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем потребовалось делать один метод в другом?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исключительно для организации кода. Внутренняя функция не используется нигде больше, она максимально "локальная", сокрыта от внешнего контекста

def is_column_name_suitable_for_index(column_name: str) -> bool:
return any(key in column_name.lower() for key in possible_idx_keywords)

columns_to_drop = copy(columns_to_drop) or []
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем их копировать?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Collaborator

@aPovidlo aPovidlo Jan 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так в области функции он же не должен менять переменные, которые находятся вне её? Еще копируешь через copy(), а она копирует только ссылки на объект, находящиеся в оригинале. При этом копируешь в туже самую переменную. columns_to_drop ты никак не изменяешь далее в функции.

Copy link
Collaborator Author

@MorrisNein MorrisNein Jan 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В питоне мутабельные объекты передаются по ссылке. Т.е. списки вполне изменяются функцией.

За внутренние объекты списка мы тут не беспокоимся, это немутабельные строки или инты.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, действительно, columns_to_drop не изменяю, сделал по аналогии с columns_to_use из-за строки

columns_to_use.append(index_col)

@@ -177,4 +181,5 @@ def data_strategy_selector(features, target, ml_task: Task = None, is_predict: b
pd.DataFrame: PandasStrategy,
np.ndarray: NumpyStrategy,
str: CsvStrategy,
PathLike: CsvStrategy,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А может сделать какой-то выбор? Хотелось бы чтобы по пути не только csv умело открывать, но и numpy массивы. Мб выбирать стратегию от формата файла в конце пути?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не знаком с форматом сохранения numpy-массивов на диск. Это часто используется?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Формат файла .npy. В некоторых экспериментах для одной компании, частично данные хранятся в таких файлах

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Под такую фичу хорошо бы отдельный PR сделать

@MorrisNein MorrisNein merged commit aa4fdd3 into master Jan 30, 2023
@MorrisNein MorrisNein deleted the api_improvements branch January 30, 2023 19:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Anything related to user-facing interfaces & parameter passing
Projects
None yet
4 participants