Тримайте все під контролем за допомогою колекцій
Зберігайте контент і організовуйте його за категоріями відповідно до своїх потреб.
У всіх хороших проектах із розробки програмного забезпечення передбачено багато часу на тестування додатків. Тому й ми наполегливо рекомендуємо протестувати вашу модель машинного навчання, щоб визначити, наскільки її прогнози правильні.
Набори даних для навчання, перевірки й тестування
Варто протестувати модель на наборі прикладів, відмінних від тих, що використовуються для її навчання. Трохи пізніше ви дізнаєтеся, що найкраще перевіряти придатність моделі, тестуючи її на різних прикладах, ніж на одному їх наборі.
Звідки взяти різні приклади? У машинному навчанні традиційно отримують різні приклади, розділяючи первинний набір даних. Тому можна припустити, що слід розділити первинний набір даних на дві підмножини:
Припустімо, що ви тренуєте модель на навчальному наборі й оцінюєте її на тестовому наборі кілька циклів. У кожному циклі ви використовуєте результати тестового набору, щоб зрозуміти, як оновити гіперпараметри й набір ознак. Чи є, на вашу думку, у цьому підході якісь недоліки? Виберіть лише одну відповідь.
Багато циклів цієї процедури може спричинити неявне пристосування моделі до особливостей конкретного набору для тестування.
Так. Що частіше ви використовуєте той самий тестовий набір, то більша ймовірність, що модель пристосується до нього.
Подібно до студента, який "готується до екзамену", модель ненавмисно пристосовується до набору даних для тестування, що може ускладнити її роботу з реальними даними.
Такий підхід є непоганим, адже ви тренуєте модель на наборі для навчання, а для оцінювання використовуєте окремий тестовий набір.
Власне, є маленький недолік. Подумайте, що може поступово піти не так.
Цей підхід неефективний із погляду обчислень. Не змінюйте гіперпараметри чи набори ознак після кожного циклу тестування.
Часто проводити тестування дорого, але необхідно. І це значно дешевше, ніж додаткове навчання. Оптимізація гіперпараметрів і набору ознак може значно покращити якість моделі, тому завжди плануйте час і обчислювальні ресурси на таку роботу.
Поділити набір даних на два набори є непоганою ідеєю, але краще розділити його на три підмножини.
На додаток до навчальної і тестової підмножини, третьою стане набір даних для перевірки.
Використовуйте набір для перевірки, щоб оцінити результати, отримані на основі набору для навчання.
Якщо після неодноразового використання набору для перевірки можна зробити висновок, що ваша модель робить хороші прогнози, скористайтеся набором для тестування, щоб іще раз переконатися в цьому.
На рисунку, наведеному нижче, показано цей робочий процес.
"Коригувати модель" означає вносити поправки в будь-які її частини, зокрема змінювати швидкість навчання, додавати чи видаляти ознаки й навіть розробляти зовсім нову модель із нуля.
Наприкінці цього робочого процесу ви виберете модель, яка показала найкращі результати на тестовому наборі даних.
Рисунок 10. Хороший робочий процес для розробки й тестування.
Робочий процес, показаний на рисунку 10, є оптимальним, але навіть із його використанням набори даних для тестування й перевірки "зношуються", якщо застосовувати їх багато разів.
Тобто що більше ви використовуєте ті самі дані, щоб приймати рішення щодо налаштувань гіперпараметрів або інших удосконалень моделі, то менше впевненості в тому, що модель створюватиме хороші прогнози на основі нових даних.
Тому доцільно зібрати більше даних, щоб "оновлювати" ними набори для тестування й перевірки. Почати заново – це чудовий спосіб перезавантаження процесу.
Вправа. Перевірте свою інтуїцію
Ви перемішали всі приклади набору даних і розділили їх на підмножини для навчання, перевірки й тестування. Однак значення втрат у вашому тестовому наборі настільки низьке, що ви підозрюєте помилку. Що могло піти не так?
У тестовому й навчальному наборах багато однакових прикладів.
Так. Ця проблема може виникнути, якщо в наборі даних багато зайвих прикладів. Наполегливо рекомендуємо видаляти повторювані приклади з тестового набору перед тестуванням.
Навчання й тестування є недетермінованими. Іноді (випадково) втрати при тестуванні можуть бути неймовірно низькими. Перезапустіть тест, щоб підтвердити результат.
Хоча рівень втрат дещо змінюється з кожним запуском, він не має відрізнятися настільки, що ви думаєте, що виграли в лотерею машинного навчання.
Так сталося, що в тестовому наборі були приклади, на основі яких модель показала хороші результати.
Приклади було добре перемішано, тому це вкрай малоймовірно.
Інші проблеми з наборами даних для тестування
Як зазначено в попередньому запитанні, повторювані приклади можуть вплинути на оцінювання моделі.
Розділивши набір даних на підмножини для навчання, перевірки й тестування, видаліть із двох останніх ті приклади, які є в навчальній. Перевірка моделі об’єктивна, тільки якщо для неї використовуються нові, а не повторювані приклади.
Наприклад, розгляньмо модель, яка прогнозує, чи електронний лист є спамом, використовуючи рядок теми, текст листа й адресу відправника як ознаки.
Припустімо, ви розділили дані на навчальний і тестовий набори, використовуючи співвідношення 80:20.
Після навчання модель досягла 99% влучності на основі даних як із навчального, так і з тестового набору. Ви очікували нижчої влучності для тестового набору, тому ще раз перевірили дані й виявили, що в ньому й у навчальному наборі багато однакових прикладів. Проблема полягає в тому, що ви не видалили повторювані записи для одного й того самого електронного листа зі спамом із вхідної бази даних перед розділенням. Ви ненавмисно проводили навчання на частині тестових даних.
Якщо підбити підсумок, хороший набір для тестування або перевірки відповідає всім критеріям, перерахованим нижче.
Досить великий, щоб можна було отримати статистично значущі результати тестування.
Загалом репрезентує набір даних. Іншими словами, не слід вибирати тестовий набір з іншими характеристиками, ніж у навчальному.
Репрезентує реальні дані, які модель отримуватиме в рамках свого робочого призначення.
Не має прикладів, які є в навчальному наборі.
Вправи. Перевірте свої знання
Якщо є один набір даних із фіксованою кількістю прикладів, яке з тверджень, наведених нижче, правдиве?
З кожним прикладом, який додається в набір для тестування моделі, на один менше використовується для її навчання.
Розподіл прикладів на набори для навчання, тестування й перевірки як перетягування ковдри.
Це основна дилема.
У тестовому наборі має бути більше прикладів, ніж у наборі для перевірки.
Теоретично набори даних для перевірки й тестування мають містити однакову або майже однакову кількість прикладів.
У тестовому наборі має бути більше прикладів, ніж у наборі для перевірки або навчання.
У наборі для навчання зазвичай більше прикладів, ніж у наборі для перевірки або тестовому; однак немає вимог щодо процентного співвідношення між ними.
Припустімо, що ваш набір для тестування містить достатньо прикладів, щоб провести статистично значуще тестування. Ба більше, тестування на його основі показало низькі втрати. Однак результати моделі на реальних даних були погані. Що робити?
Визначити, чим первинний набір відрізняється від реальних даних.
Так. Навіть найкращі набори даних є лише відображенням реальних даних; істинні дані мають тенденцію змінюватися із часом. Тестовий набір досить добре збігався з навчальним, через що здавалося, що якість моделі гарна, проте він, імовірно, недостатньо відповідає реальним даним.
Можливо, вам доведеться повторно провести навчання й тестування на новому наборі даних.
Повторно провести тестування, використовуючи той самий набір даних. Результати тестування могли бути аномалією.
Повторне тестування може дати дещо інші результати, проте тактика навряд чи буде корисною.
Скільки прикладів має містити набір даних для тестування?
Достатню кількість для проведення статистично значущого тестування.
Так. Але скільки це прикладів? Вам доведеться експериментувати.
Принаймні 15% від первинного набору даних.
Не можна сказати, що 15% прикладів точно буде достатньо.
[null,null,["Останнє оновлення: 2025-04-22 (UTC)."],[[["\u003cp\u003eMachine learning models should be tested against a separate dataset, called the test set, to ensure accurate predictions on unseen data.\u003c/p\u003e\n"],["\u003cp\u003eIt's recommended to split the dataset into three subsets: training, validation, and test sets, with the validation set used for initial testing during training and the test set used for final evaluation.\u003c/p\u003e\n"],["\u003cp\u003eThe validation and test sets can "wear out" with repeated use, requiring fresh data to maintain reliable evaluation results.\u003c/p\u003e\n"],["\u003cp\u003eA good test set is statistically significant, representative of the dataset and real-world data, and contains no duplicates from the training set.\u003c/p\u003e\n"],["\u003cp\u003eIt's crucial to address discrepancies between the dataset used for training and testing and the real-world data the model will encounter to achieve satisfactory real-world performance.\u003c/p\u003e\n"]]],[],null,["# Datasets: Dividing the original dataset\n\nAll good software engineering projects devote considerable energy to\n*testing* their apps. Similarly, we strongly recommend testing your\nML model to determine the correctness of its predictions.\n\nTraining, validation, and test sets\n-----------------------------------\n\nYou should test a model against a *different* set of examples than those\nused to train the model. As you'll learn\n[a little later](#additional_problems_with_test_sets), testing\non different examples is stronger proof of your model's fitness than testing\non the same set of examples.\nWhere do you get those different examples? Traditionally in machine learning,\nyou get those different examples by splitting the original dataset. You might\nassume, therefore, that you should split the original dataset into two subsets:\n\n- A [**training set**](/machine-learning/glossary#training-set) that the model trains on.\n- A [**test set**](/machine-learning/glossary#test-set) for evaluation of the trained model.\n\n**Figure 8.** Not an optimal split.\n\n### Exercise: Check your intuition\n\nSuppose you train on the training set and evaluate on the test set over multiple rounds. In each round, you use the test set results to guide how to update hyperparameters and the feature set. Can you see anything wrong with this approach? Pick only one answer. \nDoing many rounds of this procedure might cause the model to implicitly fit the peculiarities of the test set. \nYes! The more often you use the same test set, the more likely the model closely fits the test set. Like a teacher \"teaching to the test,\" the model inadvertently fits the test set, which might make it harder for the model to fit real-world data. \nThis approach is fine. After all, you're training on the training set and evaluating on a separate test set. \nActually, there's a subtle issue here. Think about what might gradually go wrong. \nThis approach is computationally inefficient. Don't change hyperparameters or feature sets after each round of testing. \nFrequent testing is expensive but critical. However, frequent testing is far less expensive than additional training. Optimizing hyperparameters and the feature set can dramatically improve model quality, so always budget time and computational resources to work on these.\n\nDividing the dataset into two sets is a decent idea, but\na better approach is to divide the dataset into *three* subsets.\nIn addition to the training set and the test set, the third subset is:\n\n- A [**validation set**](/machine-learning/glossary#validation-set) performs the initial testing on the model as it is being trained.\n\n**Figure 9.** A much better split.\n\nUse the **validation set** to evaluate results from the training set.\nAfter repeated use of the validation set suggests that your model is\nmaking good predictions, use the test set to double-check your model.\n\nThe following figure suggests this workflow.\nIn the figure, \"Tweak model\" means adjusting anything about the model\n---from changing the learning rate, to adding or removing\nfeatures, to designing a completely new model from scratch.\n**Figure 10.** A good workflow for development and testing. **Note:** When you transform a feature in your training set, you must make the *same* transformation in the validation set, test set, and real-world dataset.\n\nThe workflow shown in Figure 10 is optimal, but even with that workflow,\ntest sets and validation sets still \"wear out\" with repeated use.\nThat is, the more you use the same data to make decisions about\nhyperparameter settings or other model improvements, the less confidence\nthat the model will make good predictions on new data.\nFor this reason, it's a good idea to collect more data to \"refresh\" the test\nset and validation set. Starting anew is a great reset.\n\n### Exercise: Check your intuition\n\nYou shuffled all the examples in the dataset and divided the shuffled examples into training, validation, and test sets. However, the loss value on your test set is so staggeringly low that you suspect a mistake. What might have gone wrong? \nMany of the examples in the test set are duplicates of examples in the training set. \nYes. This can be a problem in a dataset with a lot of redundant examples. We strongly recommend deleting duplicate examples from the test set before testing. \nTraining and testing are nondeterministic. Sometimes, by chance, your test loss is incredibly low. Rerun the test to confirm the result. \nAlthough loss does vary a little on each run, it shouldn't vary so much that you think you won the machine learning lottery. \nBy chance, the test set just happened to contain examples that the model performed well on. \nThe examples were well shuffled, so this is extremely unlikely.\n\nAdditional problems with test sets\n----------------------------------\n\nAs the previous question illustrates, duplicate examples can affect model evaluation.\nAfter splitting a dataset into training, validation, and test sets,\ndelete any examples in the validation set or test set that are duplicates of\nexamples in the training set. The only fair test of a model is against\nnew examples, not duplicates.\n\nFor example, consider a model that predicts whether an email is spam, using\nthe subject line, email body, and sender's email address as features.\nSuppose you divide the data into training and test sets, with an 80-20 split.\nAfter training, the model achieves 99% precision on both the training set and\nthe test set. You'd probably expect a lower precision on the test set, so you\ntake another look at the data and discover that many of the examples in the test\nset are duplicates of examples in the training set. The problem is that you\nneglected to scrub duplicate entries for the same spam email from your input\ndatabase before splitting the data. You've inadvertently trained on some of\nyour test data.\n\nIn summary, a good test set or validation set meets all of the\nfollowing criteria:\n\n- Large enough to yield statistically significant testing results.\n- Representative of the dataset as a whole. In other words, don't pick a test set with different characteristics than the training set.\n- Representative of the real-world data that the model will encounter as part of its business purpose.\n- Zero examples duplicated in the training set.\n\n### Exercises: Check your understanding\n\nGiven a single dataset with a fixed number of examples, which of the following statements is true? \nEvery example used in testing the model is one less example used in training the model. \nDividing examples into train/test/validation sets is a zero-sum game. This is the central trade-off. \nThe number of examples in the test set must be greater than the number of examples in the validation set. \nIn theory, the validation set and test test should contain the same number of examples or nearly so. \nThe number of examples in the test set must be greater than the number of examples in the validation set or training set. \nThe number of examples in the training set is usually greater than the number of examples in the validation set or test set; however, there are no percentage requirements for the different sets. \nSuppose your test set contains enough examples to perform a statistically significant test. Furthermore, testing against the test set yields low loss. However, the model performed poorly in the real world. What should you do? \nDetermine how the original dataset differs from real-life data. \nYes. Even the best datasets are only a snapshot of real-life data; the underlying [ground truth](/machine-learning/glossary#ground-truth) tends to change over time. Although your test set matched your training set well enough to suggest good model quality, your dataset probably doesn't adequately match real-world data. You might have to retrain and retest against a new dataset. \nRetest on the same test set. The test results might have been an anomaly. \nAlthough retesting might yield slightly different results, this tactic probably isn't very helpful. \nHow many examples should the test set contain? \nEnough examples to yield a statistically significant test. \nYes. How many examples is that? You'll need to experiment. \nAt least 15% of the original dataset. \n15% may or may not be enough examples.\n| **Key terms:**\n|\n| - [Test set](/machine-learning/glossary#test-set)\n| - [Training set](/machine-learning/glossary#training-set)\n- [Validation set](/machine-learning/glossary#validation_set) \n[Help Center](https://support.google.com/machinelearningeducation)"]]