Является ли настройка гиперпараметра на образце набора данных плохой идеей?


19

У меня есть набор данных из 140000 примеров и 30 функций, для которых я готовлю несколько классификаторов для двоичной классификации (SVM, логистическая регрессия, случайный лес и т. Д.)

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

Я начал использовать следующую технику

  • Подвыборка моего набора данных
  • Используйте полученную дробь для настройки гиперпараметров на
  • Используйте полученные параметры для обучения модели с использованием всего набора данных

Для оценки каждого набора параметров на втором шаге я использую sklearns GridSearchCVс cv = 10. Чтобы оценить окончательную модель, которую я создаю на третьем шаге, я использую sklearns cross_val_predict. В этом смысле я оцениваю свои модели, опуская 10% процентов данных, тренируюсь на остальных и измеряю точность прогнозирования на 10%, итеративно 10 раз, а затем беру среднее из баллов.

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

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

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

Best parameters set found on development set:
{'kernel': 'rbf', 'C': 9, 'gamma': 0.1}
Scores for all sets of parameters
0.851 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.5}
0.852 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.1}
0.829 (+/-0.006) for {'kernel': 'rbf', 'C': 3, 'gamma': 0.001}
0.853 (+/-0.006) for {'kernel': 'rbf', 'C': 9, 'gamma': 0.1}
...

А вот усредненные оценки (из cross_val_predict), которые я получил от тренировок по всему набору данных, используя лучшие параметры

precision    recall  f1-score   support

      0       0.86      0.85      0.86     15417
      1       0.86      0.87      0.87     16561

avg / total       0.86      0.86      0.86     31978

acc score: 0.863750078179
roc au score: 0.863370490059
[[13147  2270]
 [ 2087 14474]]

Как вы видите, тренировка по всему набору данных улучшает результаты. Я также подтвердил, что плохо настроенная модель (например, использование значений по умолчанию или случайных значений для Cи gamma) приводит к гораздо худшей точности прогноза.

В целом, я думаю, что настройка гиперпараметров для подмножества не идеальна, но потенциально может привести к относительно хорошим результатам без необходимости ждать слишком долго. Я, например, перед использованием этого подхода использовал optunityпакет для настройки гиперпараметра во всем наборе данных. Эта процедура заняла бы 3-5 дней и дала бы результаты, которые имели либо очень хорошую точность, либо действительно хороший отзыв, но не оба, поэтому, хотя для каждого класса либо точность, либо отзыв были действительно высокими (выше, чем у любого другого из моих классификаторы достигли) мера f1 была действительно низкой. Напротив, использование более позднего подхода приводит к нескольким часам тренировок и лучшему измерению f1.

Мои опасения:

Я ограничиваю свою точность классификации? Избегаю ли я использовать все возможности прогнозирования, которые может предложить мой набор данных, настраивая только на подмножество? Если такой вред производительности происходит, это как-то ограничено каким-то фактором?


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

Смотрите мой обновленный вопрос. Надеюсь, теперь стало понятнее.
LetsPlayYahtzee

Ответы:


15

In addition to Jim's (+1) answer: For some classifiers, the hyper-parameter values are dependent on the number of training examples, for instance for a linear SVM, the primal optimization problem is

min12w2+Ci=1ξi

subject to

yi(xiwb)1ξi,andξi0i

Note that the optimisation problem is basically a measure of the data mis-fit term (the summation over ξi) and a regularisation term, but the usual regrularisation parameter is placed with the data misfit term. Obviously the greater the number of training patterns we have, the larger the summation will be and the smaller C ought to be to maintain the same balance with the magnitude of the weights.

Some implementations of the SVM reparameterise as

min12w2+Ci=1ξi

in order to compensate, but some don't. So an additional point to consider is whether the optimal hyper-parameters depend on the number of training examples or not.

I agree with Jim that overfitting the model selection criterion is likely to be more of an issue, but if you have enough data even in the subsample then this may not be a substantial issue.


11

Is hyperparameter tuning on sample of dataset a bad idea?

A: Yes, because you risk overfitting (the hyperparameters) on that specific test set resulting from your chosen train-test split.

Do I limit my classification accuracy?

A: Yes, but common machine learning wisdom is: with your optimal hyperparameters, say λ, refit your model(s) on the whole dataset and make that model your final model for new, unseen, future cases.

Do I avoid using all the prediction power that my dataset can offer by tuning only on a subset?

A: see previous answer.

If such a harm of performance is happening is it somehow limited by some factor?

A: idem.

I measure my accuracy using 10-fold cross as I use to also evaluate the parameters

A: Note that this is different from what is asked in the title. 10-fold CV iterates over 10 test-train splits to arrive at an "unbiased" (less-biased) estimate of generalizability (measured in this case by accuracy). 10-fold CV exactly addresses the issue I talk about in the first answer.

the prediction accuracy I get from training on my whole dataset

A: this is an "in-sample" measure that could be optimistically biased. But don't forget that you have many cases and relatively few features, so that this optimism bias may not be an issue. Machine learning nugget: "the best regularizer is more data."

[cont'd], is always really close to the evaluation I get when tuning the parameters for the best set of parameters.

A: see previous answer. Look at the hyperparameter plots: does tuning decrease error and by how much? From what you are saying, the tuning is not doing much.

You could test this as follows. Take a 70%-30% train-test split. Compare predictive performance of:

  1. an untuned model trained on the train set,
  2. a 10-fold-CV tuned model trained on the train set.

Let both models predict the test set. If performance is very close, then tuning is not doing much. If performance is different in favor of the tuned model, then continue with the tuning approach.


1

I'll answer for artificial neural networks (ANNs).

The hyperparameters of ANNs may define either its learning process (e.g., learning rate or mini-batch size) or its architecture (e.g., number of hidden units or layers).

Tuning architectural hyperparameters on a subset of your training set is probably not a good idea (unless your training set really lacks diversity, i.e. increasing the training set size doesn't increase the ANN performance), since architectural hyperparameters change the capacity of the ANN.

I would be less concerned tuning the hyperparameters that define the learning process on a subset of your training set, but I guess one should validate it empirically.



0

You can use hyperparameter optimization algorithms which support multifidelity evaluations, i.e., evaluations on sub-sets of your data in order to get a rough but useful estimate about optimal hyperparameter values for the entire dataset. Such approaches typically allow to the reduce the total computational cost needed to run hyperparameter optimization.


Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.