우수한 소프트웨어 엔지니어링 프로젝트는 모두 앱 테스트에 상당한 노력을 기울입니다. 마찬가지로 ML 모델을 테스트하여 예측의 정확성을 확인하는 것이 좋습니다.
학습, 검증, 테스트 세트
모델을 학습하는 데 사용된 예시와 다른 예시를 사용하여 모델을 테스트해야 합니다. 조금 후에 알아볼 수 있듯이, 동일한 예시 세트를 테스트하는 것보다 다양한 예시를 테스트하는 것이 모델의 적합성을 더 강력하게 증명합니다. 다양한 예시는 어디에서 가져오나요? 기존 머신러닝에서는 원본 데이터 세트를 분할하여 이러한 다양한 예시를 얻었습니다. 따라서 원래 데이터 세트를 두 개의 하위 집합으로 분할해야 한다고 가정할 수 있습니다.
검증 세트를 사용하여 학습 세트의 결과를 평가합니다. 검증 세트를 반복적으로 사용한 결과 모델이 좋은 예측을 하고 있다고 판단되면 테스트 세트를 사용하여 모델을 다시 한번 확인합니다.
다음 그림은 이 워크플로를 보여줍니다. 그림에서 '모델 조정'은 학습률 변경, 기능 추가 또는 삭제, 완전히 새로운 모델을 처음부터 설계하는 등 모델에 관한 모든 것을 조정하는 것을 의미합니다.
그림 10. 개발 및 테스트에 적합한 워크플로
그림 10에 표시된 워크플로가 최적이지만 이 워크플로를 사용하더라도 테스트 세트와 검증 세트는 반복적으로 사용하면 '마모'됩니다. 즉, 동일한 데이터를 사용하여 초매개변수 설정이나 기타 모델 개선사항에 관해 결정할수록 모델이 새 데이터에 관해 정확한 예측을 할 확률이 낮아집니다. 따라서 테스트 세트와 검증 세트를 '새로고침'하기 위해 더 많은 데이터를 수집하는 것이 좋습니다. 새롭게 시작하는 것은 좋은 재설정입니다.
연습문제: 직관력 테스트
데이터 세트의 모든 예시를 셔플하고 셔플된 예시를 학습, 검증, 테스트 세트로 분할했습니다. 하지만 테스트 세트의 손실 값이 너무 낮아 실수가 있다고 생각합니다. 어떤 문제가 발생했을까요?
테스트 세트의 예시 중 상당수가 학습 세트의 예시와 중복됩니다.
예. 중복 예시가 많은 데이터 세트에서는 문제가 될 수 있습니다. 테스트하기 전에 테스트 세트에서 중복 예시를 삭제하는 것이 좋습니다.
학습 및 테스트는 비결정론적입니다. 우연히 테스트 손실이 매우 낮은 경우가 있습니다. 테스트를 다시 실행하여 결과를 확인합니다.
손실은 실행마다 약간 다르지만 머신러닝 복권에 당첨되었다고 생각할 만큼 크게 달라서는 안 됩니다.
우연히 테스트 세트에 모델의 성능이 우수한 예시가 포함되었습니다.
예시가 잘 섞여 있으므로 이러한 가능성은 매우 낮습니다.
테스트 세트의 추가 문제
이전 질문에서 설명한 것처럼 중복 예시는 모델 평가에 영향을 줄 수 있습니다. 데이터 세트를 학습, 검증, 테스트 세트로 분할한 후 검증 세트 또는 테스트 세트에서 학습 세트의 예시와 중복되는 예시를 삭제합니다. 모델을 공정하게 테스트하는 유일한 방법은 중복이 아닌 새 예시를 사용하는 것입니다.
예를 들어 제목, 이메일 본문, 발신자의 이메일 주소를 특성으로 사용하여 이메일이 스팸인지 여부를 예측하는 모델을 생각해 보세요. 데이터를 80-20 분할로 학습 세트와 테스트 세트로 나눈다고 가정해 보겠습니다. 학습 후 모델은 학습 세트와 테스트 세트 모두에서 99% 의 정밀도를 달성합니다. 테스트 세트의 정밀도가 더 낮을 것으로 예상되므로 데이터를 다시 살펴본 결과 테스트 세트의 예시 중 상당수가 학습 세트의 예시와 중복되는 것으로 확인됩니다. 문제는 데이터를 분할하기 전에 입력 데이터베이스에서 동일한 스팸 이메일의 중복 항목을 삭제하지 않은 것입니다. 실수로 일부 테스트 데이터를 학습했습니다.
요약하자면 좋은 테스트 세트 또는 유효성 검사 세트는 다음 기준을 모두 충족합니다.
통계적으로 유의미한 테스트 결과를 얻을 만큼 충분히 큽니다.
데이터 세트를 전체적으로 표현해야 합니다. 즉, 평가 세트가 학습 세트와 같은 특징을 가지도록 선별해야 합니다.
모델이 비즈니스 목적의 일환으로 접하게 되는 실제 데이터를 나타냅니다.
학습 세트에 중복된 예가 없습니다.
연습문제: 이해도 확인
고정된 수의 예시가 포함된 단일 데이터 세트가 주어질 때 다음 중 어느 것이 사실인가요?
모델을 테스트하는 데 사용되는 모든 예는 모델을 학습하는 데 사용되는 예보다 하나 적습니다.
예시를 학습/테스트/검증 세트로 나누는 것은 제로섬 게임입니다. 이것이 핵심적인 절충점입니다.
테스트 세트의 예시 수가 검증 세트의 예시 수보다 커야 합니다.
이론적으로 검증 세트와 테스트 세트에는 동일한 수의 예시 또는 거의 동일한 수의 예시가 포함되어야 합니다.
테스트 세트의 예시 수는 검증 세트 또는 학습 세트의 예시 수보다 커야 합니다.
학습 세트의 예 수는 일반적으로 검증 세트 또는 테스트 세트의 예 수보다 많지만, 여러 세트의 비율 요구사항은 없습니다.
테스트 세트에 통계적 유의성이 있는 테스트를 실행하기에 충분한 예시가 포함되어 있다고 가정해 보겠습니다. 또한 테스트 세트를 대상으로 테스트하면 손실이 적습니다. 하지만 실제 환경에서는 모델의 성능이 좋지 않았습니다. 어떻게 해야 할까요?
원본 데이터 세트와 실제 데이터의 차이를 파악합니다.
예. 가장 우수한 데이터 세트도 실제 데이터의 스냅샷일 뿐입니다. 기본 실측값은 시간이 지남에 따라 변경되는 경향이 있습니다. 테스트 세트가 학습 세트와 잘 일치하여 모델 품질이 양호하다고 가정할 수 있지만 데이터 세트가 실제 데이터와 충분히 일치하지 않을 수 있습니다. 새 데이터 세트를 대상으로 재학습하고 재테스트해야 할 수 있습니다.
[null,null,["최종 업데이트: 2025-01-03(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,["All 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\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\nExercise: Check your intuition \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\nExercise: Check your intuition \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\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\nExercises: Check your understanding \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)"]]