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

Add topofeatures #1241

Merged
merged 22 commits into from
Jan 15, 2024
Merged

Add topofeatures #1241

merged 22 commits into from
Jan 15, 2024

Conversation

valer1435
Copy link
Collaborator

TopologicalFeaturesImplementation was added

@pep8speaks
Copy link

pep8speaks commented Dec 28, 2023

Hello @valer1435! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 58:21: E131 continuation line unaligned for hanging indent

Comment last updated at 2023-12-28 11:36:56 UTC

Copy link

codecov bot commented Dec 28, 2023

Codecov Report

Attention: 62 lines in your changes are missing coverage. Please review.

Comparison is base (dcc7ff5) 79.97% compared to head (96c4f95) 80.05%.

Files Patch % Lines
...tations/data_operations/topological/point_cloud.py 46.29% 29 Missing ⚠️
...tions/data_operations/topological/hankel_matrix.py 63.88% 26 Missing ⚠️
...tations/data_operations/topological/topological.py 97.60% 4 Missing ⚠️
fedot/api/fedot_cli.py 0.00% 1 Missing ⚠️
fedot/core/data/data.py 0.00% 1 Missing ⚠️
...ion_intervals/solvers/mutation_of_best_pipeline.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1241      +/-   ##
==========================================
+ Coverage   79.97%   80.05%   +0.07%     
==========================================
  Files         145      149       +4     
  Lines        9945    10278     +333     
==========================================
+ Hits         7954     8228     +274     
- Misses       1991     2050      +59     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@kasyanovse kasyanovse left a comment

Choose a reason for hiding this comment

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

До конца не досмотрел. Давай сначала найденные моменты уточним.
Вообще, кажется, что местами итерирование по спискам можно заменить на работу с np.ndarray, что значительно ускорит топологические признаки.
И смущает полное отсутствие тестов для всех новых объектов. Мне кажется, что нужно покрыть все объекты и основные методы.

@@ -44,7 +46,8 @@ class FedotPreprocessingStrategy(EvaluationStrategy):
'poly_features': PolyFeaturesImplementation,
'one_hot_encoding': OneHotEncodingImplementation,
'label_encoding': LabelEncodingImplementation,
'fast_ica': FastICAImplementation
'fast_ica': FastICAImplementation,
'topological_features': TopologicalFeaturesImplementation
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.

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

from scipy.linalg import hankel


class HankelMatrix:
Copy link
Collaborator

Choose a reason for hiding this comment

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

А в чем глобальная разница между этим классом и LaggedImplementation?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

На самом деле ни в чем) Не было времени реализовать с момощью нашего лаг преобразования


@staticmethod
def __create_epsilon_range(epsilon):
return np.array([y * float(1 / epsilon) for y in range(epsilon)])
Copy link
Collaborator

Choose a reason for hiding this comment

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

Зачем float? Почему не np.arange(epsilon) / epsilon?

Comment on lines +67 to +68
if self.__window_length is None:
self.__window_length = dimension_embed
Copy link
Collaborator

Choose a reason for hiding this comment

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

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

Comment on lines +95 to +97
diagrams = [np.array([dg for dg in diag if np.isfinite(dg).all()]) for diag in diagrams]
diagrams = diagrams / max(
[np.array([dg for dg in diag if np.isfinite(dg).all()]).max() for diag in diagrams if diag.shape[0] > 0])
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.

Это скорее всего что-то старое и неиспользуемое) Удалил

feature_list.append(x_features)
for dim in range(len(x_features)):
column_list.append('{}_{}'.format(feature_name, dim))
except Exception:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Из-за чего код может упасть?

x_features = feature_model.fit_transform(x_pers_diag)
feature_list.append(x_features)
for dim in range(len(x_features)):
column_list.append('{}_{}'.format(feature_name, dim))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Если не ошибаюсь, то f-строки быстрее, чем format.

for dim in range(len(x_features)):
column_list.append('{}_{}'.format(feature_name, dim))
continue
x_transformed = pd.DataFrame(data=np.hstack(feature_list)).T
Copy link
Collaborator

Choose a reason for hiding this comment

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

В FEDOT не используются pd.DataFrame, ИМХО безопаснее везде использовать np.ndarray, чтобы случайно не словить где-нибудь ошибку.

for hole in persistence_diagram:
index = int(hole[2])
lifetime = hole[1] - hole[0]
if np.equal(lifetime, self.ratio_ * max_lifetimes[index]):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Почему через np.equal?

super(PersistenceEntropyFeature).__init__()

def extract_feature_(self, persistence_diagram):
persistence_entropy = PersistenceEntropy(n_jobs=-1)
Copy link
Collaborator

Choose a reason for hiding this comment

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

По умолчанию все ноды в FEDOT работают в один поток, т.к. распараллеливание осуществляется на уровне пайплайнов.

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

Choose a reason for hiding this comment

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

Может быть попробовать оптимизировать? Накладные расходы на работу с огромным количеством потоков (в пределе это n_cpu ** n_cpu) никто не отменял.

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 Author

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.

Не выйдет, так как не все операции векторизуются в контексте оптимизации времени. np.vectorise не ускоряет выполнение

Copy link
Collaborator

Choose a reason for hiding this comment

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

Я имел ввиду векторизацию в виде использования чистых numpy функций над одним многомерным np.ndarray.
Но тут надо разбираться как это можно реализовать.

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 Author

Choose a reason for hiding this comment

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

Тем более код не мой, я скорее его адаптирую для федота

Copy link
Collaborator

Choose a reason for hiding this comment

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

Выхлоп - экономия времени на каждом запуске топо внутри каждого пайплайна внутри каждого поколения для каждой оптимизации в каждом запуске федота. Выгода даже в 10% достаточна)) ИМХО.
Я могу помочь с адаптацией, но не в срочном порядке.

Copy link
Contributor

github-actions bot commented Jan 10, 2024

All PEP8 errors has been fixed, thanks ❤️

Comment last updated at

@valer1435
Copy link
Collaborator Author

/fix-pep8

Comment on lines 33 to 34
if not m4_id:
label = random.choice(np.unique(time_series['label']))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Поставь ограничение на длину датасета, пожалуйста. Если он слишком короткий, то там много проблем с композицией пайплайнов возникает, которые корректно отрабатываются в проде, но падают на тесте. Я бы поставил длину ряда в районе 1000 точек - с ней все хорошо. С длиной до 400 очень часто падает.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

В тестах используются старые датасеты (beer, salaries и тд)

@valer1435
Copy link
Collaborator Author

/fix-pep8

@kasyanovse kasyanovse self-requested a review January 15, 2024 10:47
@valer1435
Copy link
Collaborator Author

/fix-pep8

@valer1435
Copy link
Collaborator Author

/fix-pep8

@valer1435 valer1435 merged commit a4ef39e into master Jan 15, 2024
7 checks passed
@valer1435 valer1435 deleted the add_topo2 branch January 15, 2024 19:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants