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

CropToDataRange model implementation and use example #1090

Closed
wants to merge 4 commits into from

Conversation

ChrisLisbon
Copy link
Collaborator

CropToDataRange model for regression and ts_prediction task which crop prediction to min and max data range with sigma uncertainty. This helps reduce error if is known that data belongs to range and cant be out of it.

Sigma_min and sigma_max - hyperparameters for optimization (if min and max not presented in train data).

Example demonstrates initial pipeline composing and tuning through methods (not API) for ice concentration prediction.

@aim-pep8-bot
Copy link

aim-pep8-bot commented Apr 25, 2023

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

Line 15:1: F401 'fedot.core.repository.quality_metrics_repository.RegressionMetricsEnum' imported but unused
Line 114:38: E226 missing whitespace around arithmetic operator
Line 175:1: E265 block comment should start with '# '

Comment last updated at 2023-04-28 10:30:10 UTC

"presets": ["fast_train", "ts"],
"tags": [
"simple",
"non_linear"
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.

Ну non_linear наверное можно убрать, а так вроде норм.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

это просто дефолтный тег и какой-то из них нужно выбрать, иначе тест падает


pass

def predict(self, input_data: InputData) -> OutputData:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Опиши хотя бы тут что имеется в виду по сигма.

lag2 = PipelineNode('lagged')
r1 = PipelineNode('ridge', nodes_from=[lag1])
r2 = PipelineNode('ridge', nodes_from=[lag2])
r3 = PipelineNode('ridge', nodes_from=[r1, r2])
Copy link
Collaborator

Choose a reason for hiding this comment

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

Оставлю, как подсказку-пример, как такой пайплайн можно реализовать с помощью билдера:
pipeline= PipelineBuilder().add_node('lagged', branch_idx=1).add_node('ridge', branch_idx=1)
.add_node('lagged', branch_idx=2).add_node('ridge', branch_idx=2).join_branches('ridge').add_node('crop_range').build()

Что-то такое

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

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

return rmse, mae


def compose_pipeline(pipeline, train_data, task):
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.

потому что через api падает. Мы это обсуждали, какие-то проблемы в големе в процессе фикса как я поняла

return tuned_pipeline


df = pd.read_csv('../../data/ts/osisaf_ice_conc.csv')
Copy link
Collaborator

Choose a reason for hiding this comment

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

Это лучше выделить в отдельную функцию main и вызывать через if name == 'main':

prediction = pipeline.predict(predict_input)
prediction_values = np.ravel(np.array(prediction.predict))

rmse_tuning, mae_tuning = calculate_metrics(np.ravel(predict_input.target), prediction_values)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Подсчет метрик тоже упростился бы при использовании апи (используя get_metrics())

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

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

rmse_tuning, mae_tuning = calculate_metrics(np.ravel(predict_input.target), prediction_values)
plt.plot(np.ravel(predict_input.idx), np.ravel(predict_input.target), label='test')
plt.plot(np.ravel(train_input.idx)[-1300:], np.ravel(train_input.target)[-1300:], label='history')
plt.plot(np.ravel(predict_input.idx), prediction_values, label='prediction_after_tuning')
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут тоже при использовании апи можно было бы вызвать plot_prediction

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Он не позволяет отрезать диапазон так, как я это сделала для наглядности

sigma_min = self.params.get('sigma_min')
sigma_max = self.params.get('sigma_max')

min_value = self.params.get('min_value')
Copy link
Collaborator

Choose a reason for hiding this comment

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

В какой момент параметры min_value и max_value приходят в self.params? Подозреваю, что это могут быть минимальные и максимальные значения трейн части.

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.

Потому что пользователь может обладать экспертными знаниями о том, что параметр не выходит за рамки диапазона. В данном случае концентрация льда не может быть меньше 0 и больше 1

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.

Там два варианта: 1) ты знаешь эти границы, задаешь их вручную и добавляешь ноду сам. 2) ты не знаешь границы, но данные сами по себе не выходят за диапазон и тогда мин и макс подбирается на основе данных с допуском в сигма, и тогда эта нода может быть уместна при эволюции. Внутри реализации 4 гиперпараметра.

max_value = self.params.get('max_value')

if not min_value:
min_value = np.nanmin(np.array(input_data.target))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут полноценный даталик - ты берешь информацию о свойствах таргета.

PS еще таргета может просто не быть, тогда работать не будет

@@ -230,6 +230,14 @@
"non_linear"
]
},
"crop_range": {
Copy link
Collaborator

Choose a reason for hiding this comment

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

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

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.

А почему он может не попадаться в available_operations? Эта модель задумана для любых табличных и векторных данных, на которых может применяться регрессия, вроде бы не вижу ничего особенного в ограничениях. На эволюции эта нода добавляется, значит available

MutationTypesEnum.single_drop,
MutationTypesEnum.single_add]
)
composer = ComposerBuilder(task=task). \
Copy link
Collaborator

Choose a reason for hiding this comment

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

кажется, что стиль переносов должен быть единым. Например, как ниже в 68 строке с TunerBuilder

return tuned_pipeline


df = pd.read_csv('../../data/ts/osisaf_ice_conc.csv')
Copy link
Collaborator

Choose a reason for hiding this comment

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

относительные пути коварная штука, лучше поменять

@valer1435
Copy link
Collaborator

valer1435 commented May 2, 2023

После этого фикса работает в режиме api?

@nicl-nno
Copy link
Collaborator

nicl-nno commented May 7, 2024

Closed as obsolete

@nicl-nno nicl-nno closed this May 7, 2024
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

5 participants