과적합이란 학습 세트와 너무 유사하여 새 데이터를 올바르게 예측하지 못하는 모델을 만드는 것을 의미합니다 (학습). 과적합 모델은 실험실에서는 잘 작동하지만 실제 환경에서는 쓸모가 없는 발명품과 비슷합니다.
그림 11에서 각 도형은 정사각형 숲에 있는 나무의 위치를 나타냅니다. 파란색 다이아몬드는 건강한 나무의 위치를, 주황색 원은 아픈 나무의 위치를 표시합니다.
그림 11. 학습 세트: 정사각형 숲에 있는 건강한 나무와 아픈 나무의 위치
선, 곡선, 타원 등 어떤 도형이든 상상하여 그려 건강한 나무와 아픈 나무를 구분합니다. 그런 다음 다음 줄을 펼쳐 가능한 분리를 하나씩 살펴봅니다.
펼쳐서 가능한 해결 방법을 확인합니다 (그림 12).
그림 12. 아픈 나무와 건강한 나무를 구분하는 복잡한 모델입니다.
그림 12에 표시된 복잡한 도형은 나무 중 두 개를 제외하고 모두 분류했습니다. 도형을 모델로 생각하면 멋진 모델입니다.
정말 불가능할까요? 정말 우수한 모델은 새로운 예시를 성공적으로 분류합니다. 그림 13은 동일한 모델이 테스트 세트의 새 예시를 예측할 때 어떤 일이 일어나는지 보여줍니다.
그림 13. 테스트 세트: 아픈 나무와 건강한 나무를 구분하는 복잡한 모델입니다.
따라서 그림 12에 표시된 복잡한 모델은 학습 세트에서 매우 우수한 성능을 보였지만 테스트 세트에서는 매우 좋지 않은 성능을 보였습니다. 이는 모델이 학습 세트 데이터에 과적합하는 전형적인 사례입니다.
적합, 과적합, 과소적합
모델은 새 데이터를 잘 예측해야 합니다. 즉, 새 데이터에 '맞는' 모델을 만드는 것이 목표입니다.
보시다시피 과적합 모델은 학습 세트에서는 우수한 예측을 하지만 새 데이터에서는 예측이 좋지 않습니다. 적합도 부족 모델은 학습 데이터를 제대로 예측하지 못합니다. 과적합 모델은 실험실에서는 잘 작동하지만 실제 환경에서는 잘 작동하지 않는 제품과 같고, 언더피팅 모델은 실험실에서도 잘 작동하지 않는 제품과 같습니다.
그림 14. 과소적합, 적합, 과적합 모델
일반화는 과적합의 반대입니다. 즉, 일반화 성능이 우수한 모델은 새 데이터를 잘 예측합니다. 새로운 데이터에 잘 일반화되는 모델을 만드는 것이 목표입니다.
과적합 감지
다음 곡선을 사용하면 과적합을 감지할 수 있습니다.
손실 곡선
일반화 곡선
손실 곡선은 모델의 손실을 학습 반복 횟수에 대해 표시합니다. 두 개 이상의 손실 곡선을 보여주는 그래프를 일반화 곡선이라고 합니다. 다음 일반화 곡선은 두 가지 손실 곡선을 보여줍니다.
그림 15. 과적합을 강하게 암시하는 일반화 곡선입니다.
두 손실 곡선이 처음에는 비슷하게 동작하다가 나중에 갈라지는 것을 볼 수 있습니다. 즉, 일정 횟수의 반복 후 학습 세트의 손실은 감소하거나 일정하게 유지되지만 (수렴) 검증 세트의 손실은 증가합니다. 이는 과적합을 나타냅니다.
반대로 잘 맞는 모델의 일반화 곡선은 모양이 비슷한 두 개의 손실 곡선을 보여줍니다.
과적합의 원인은 무엇인가요?
대략적으로 오버피팅은 다음 문제 중 하나 또는 둘 다로 인해 발생합니다.
학습 세트가 실제 데이터 (또는 검증 세트 또는 테스트 세트)를 충분히 대표하지 않습니다.
모델이 너무 복잡합니다.
일반화 조건
모델은 학습 세트에서 학습하지만 모델의 가치를 실제로 테스트하려면 새 예시, 특히 실제 데이터에서 얼마나 잘 예측하는지 확인해야 합니다. 모델을 개발하는 동안 테스트 세트는 실제 데이터의 프록시 역할을 합니다. 잘 일반화되는 모델을 학습하려면 다음과 같은 데이터 세트 조건이 필요합니다.
예는 독립적이고 동일하게 분포되어야 합니다. 즉, 예가 서로 영향을 미칠 수 없다는 것을 멋진 방식으로 표현한 것입니다.
데이터 세트가 정상적입니다. 즉, 데이터 세트가 시간이 지남에 따라 크게 변경되지 않습니다.
데이터 세트 파티션의 분포가 동일합니다. 즉, 학습 세트의 예시가 검증 세트, 테스트 세트, 실제 데이터의 예시와 통계적으로 유사합니다.
다음 연습을 통해 위의 조건을 살펴보세요.
연습문제: 이해도 확인
다음과 같은 데이터 세트 파티션을 고려해 보겠습니다. 학습 세트의 예시가 검증 세트 및 테스트 세트의 예시와 유사한 통계적 분포를 갖도록 하려면 어떻게 해야 하나요?
데이터 세트의 예시를 파티션하기 전에 광범위하게 셔플합니다.
예. 예시를 잘 셔플하면 파티션이 통계적으로 유사할 가능성이 훨씬 높아집니다.
예시를 가장 오래된 것부터 가장 최근 것 순으로 정렬합니다.
데이터 세트의 예시가 정적이 아니면 정렬하면 파티션이 더 비슷하지 않게 됩니다.
아무 조치도 취하지 않습니다. 충분한 예시가 있으면 평균 법칙에 따라 분포가 통계적으로 유사해집니다.
안타깝게도 그렇지 않습니다. 데이터 세트의 특정 섹션에 있는 예시가 다른 섹션의 예시와 다를 수 있습니다.
스트리밍 서비스에서 향후 3년간 새로운 TV 프로그램의 인기를 예측하는 모델을 개발하고 있습니다. 스트리밍 서비스는 지난 10년 동안 수억 개의 예시가 포함된 데이터 세트에서 모델을 학습할 계획입니다. 이 모델에 문제가 발생하나요?
아마 그럴 거예요. 시청자의 취향은 이전 행동으로는 예측할 수 없는 방식으로 변합니다.
예. 시청자 취향은 고정되지 않습니다. 끊임없이 변화합니다.
절대 아닙니다. 데이터 세트가 충분히 커서 정확한 예측을 할 수 있습니다.
안타깝게도 시청자의 취향은 고정되지 않습니다.
그렇지 않을 수도 있습니다. 시청자의 취향은 예측 가능한 주기적인 방식으로 변화합니다. 10년간의 데이터를 사용하면 모델이 미래 동향을 정확하게 예측할 수 있습니다.
엔터테인먼트의 특정 측면은 다소 주기적이지만 과거 엔터테인먼트 기록을 바탕으로 학습된 모델은 향후 몇 년을 예측하는 데 거의 확실히 어려움을 겪을 것입니다.
한 모델은 계절에 따라 날씨가 크게 달라지는 도시에서 1년 동안 수집된 날씨 데이터 (온도, 이슬점, 강수량)를 기반으로 사람이 1마일을 걸어가는 데 걸리는 시간을 예측하는 것을 목표로 합니다. 날씨 측정값이 계절에 따라 크게 달라도 이 데이터 세트에서 모델을 빌드하고 테스트할 수 있나요?
예
예, 이 데이터 세트에서 모델을 빌드하고 테스트할 수 있습니다. 4계절의 데이터가 여러 파티션에 균등하게 분산되도록 데이터가 균등하게 분할되어 있는지만 확인하면 됩니다.
아니요
이 데이터 세트에 온도, 이슬점, 강수량의 예시가 충분히 포함되어 있다고 가정하면 이 데이터 세트에서 모델을 빌드하고 테스트할 수 있습니다. 4계절의 데이터가 여러 파티션에 균등하게 분산되도록 데이터가 균등하게 분할되어 있는지만 확인하면 됩니다.
챌린지 연습
승객이 특정 경로의 기차 티켓을 구매하기에 가장 적합한 날짜를 예측하는 모델을 만들고 있습니다. 예를 들어 모델은 사용자가 7월 23일에 출발하는 기차의 티켓을 7월 8일에 구매하도록 추천할 수 있습니다. 기차 회사는 다양한 요소를 고려하여 주로 현재 이용 가능한 좌석 수를 기준으로 매시간 가격을 업데이트합니다. 이는 다음과 같은 의미입니다.
이용 가능한 좌석이 많으면 일반적으로 티켓 가격이 낮습니다.
이용 가능한 좌석이 적은 경우 일반적으로 티켓 가격이 높습니다.
모델이 검증 세트와 테스트 세트에서 낮은 손실을 보이지만 실제 데이터에서는 잘못된 예측을 내릴 때가 있습니다. 왜냐하면
예를 들어 모델이 사용자에게 7월 8일에 티켓을 구매하도록 추천한다고 가정해 보겠습니다. 모델의 추천을 사용하는 일부 승객은 7월 8일 오전 8시 30분에 티켓을 구매합니다. 9시가 되면 기차 회사는 이용 가능한 좌석이 줄었으므로 가격을 인상합니다. 모델의 추천을 사용하는 라이더가 가격을 변경했습니다. 저녁이 되면 티켓 가격이 아침보다 훨씬 높을 수 있습니다.
[null,null,["최종 업데이트: 2024-11-14(UTC)"],[[["\u003cp\u003eOverfitting occurs when a model performs well on training data but poorly on new, unseen data.\u003c/p\u003e\n"],["\u003cp\u003eA model is considered to generalize well if it accurately predicts on new data, indicating it hasn't overfit.\u003c/p\u003e\n"],["\u003cp\u003eOverfitting can be detected by observing diverging loss curves for training and validation sets on a generalization curve.\u003c/p\u003e\n"],["\u003cp\u003eCommon causes of overfitting include unrepresentative training data and overly complex models.\u003c/p\u003e\n"],["\u003cp\u003eDataset conditions for good generalization include examples being independent, identically distributed, and stationary, with similar distributions across partitions.\u003c/p\u003e\n"]]],[],null,["# Overfitting\n\n[**Overfitting**](/machine-learning/glossary#overfitting) means creating a model\nthat matches (*memorizes* ) the\n[**training set**](/machine-learning/glossary#training-set) so\nclosely that the model fails to make correct predictions on new data.\nAn overfit model is analogous to an invention that performs well in the lab but\nis worthless in the real world.\n| **Tip:** Overfitting is a common problem in machine learning, not an academic hypothetical.\n\nIn Figure 11, imagine that each geometric shape represents a tree's position\nin a square forest. The blue diamonds mark the locations of healthy trees,\nwhile the orange circles mark the locations of sick trees.\n**Figure 11.** Training set: locations of healthy and sick trees in a square forest.\n\nMentally draw any shapes---lines, curves, ovals...anything---to separate the\nhealthy trees from the sick trees. Then, expand the next line to examine\none possible separation.\n\n#### Expand to see one possible solution (Figure 12).\n\n**Figure 12.** A complex model for distinguishing sick from healthy trees.\n\nThe complex shapes shown in Figure 12 successfully categorized all but two of\nthe trees. If we think of the shapes as a model, then this is a fantastic\nmodel.\n\nOr is it? A truly excellent model successfully categorizes *new* examples.\nFigure 13 shows what happens when that same model makes predictions on new\nexamples from the test set:\n**Figure 13.**Test set: a complex model for distinguishing sick from healthy trees.\n\nSo, the complex model shown in Figure 12 did a great job on the training set\nbut a pretty bad job on the test set. This is a classic case of a model\n*overfitting* to the training set data.\n\nFitting, overfitting, and underfitting\n--------------------------------------\n\nA model must make good predictions on *new* data.\nThat is, you're aiming to create a model that \"fits\" new data.\n\nAs you've seen, an overfit model makes excellent predictions on the training\nset but poor predictions on new data. An\n[**underfit**](/machine-learning/glossary#underfitting) model\ndoesn't even make good predictions on the training data. If an overfit model is\nlike a product that performs well in the lab but poorly in the real world,\nthen an underfit model is like a product that doesn't even do well in\nthe lab.\n**Figure 14.** Underfit, fit, and overfit models.\n\n[**Generalization**](/machine-learning/glossary#generalization) is the\nopposite of overfitting. That is, a model that *generalizes well* makes good\npredictions on new data. Your goal is to create a model that generalizes\nwell to new data.\n\nDetecting overfitting\n---------------------\n\nThe following curves help you detect overfitting:\n\n- loss curves\n- generalization curves\n\nA [**loss curve**](/machine-learning/glossary#loss-curve) plots a model's loss\nagainst the number of training iterations.\nA graph that shows two or more loss curves is called a [**generalization\ncurve**](/machine-learning/glossary#generalization-curve). The following\ngeneralization curve shows two loss curves:\n**Figure 15.** A generalization curve that strongly implies overfitting.\n\nNotice that the two loss curves behave similarly at first and then diverge.\nThat is, after a certain number of iterations, loss declines or\nholds steady (converges) for the training set, but increases\nfor the validation set. This suggests overfitting.\n\nIn contrast, a generalization curve for a well-fit model shows two loss curves\nthat have similar shapes.\n\nWhat causes overfitting?\n------------------------\n\nVery broadly speaking, overfitting is caused by one or both of the following\nproblems:\n\n- The training set doesn't adequately represent real life data (or the validation set or test set).\n- The model is too complex.\n\nGeneralization conditions\n-------------------------\n\nA model trains on a training set, but the real test of a model's worth is how\nwell it makes predictions on new examples, particularly on real-world data.\nWhile developing a model, your test set serves as a proxy for real-world data.\nTraining a model that generalizes well implies the following dataset conditions:\n\n- Examples must be [**independently and identically distributed**](/machine-learning/glossary#independently-and-identically-distributed-i.i.d), which is a fancy way of saying that your examples can't influence each other.\n- The dataset is [**stationary**](/machine-learning/glossary#stationarity), meaning the dataset doesn't change significantly over time.\n- The dataset partitions have the same distribution. That is, the examples in the training set are statistically similar to the examples in the validation set, test set, and real-world data.\n\nExplore the preceding conditions through the following exercises.\n\nExercises: Check your understanding\n-----------------------------------\n\nConsider the following dataset partitions. What should you do to ensure that the examples in the training set have a similar statistical distribution to the examples in the validation set and the test set? \nShuffle the examples in the dataset extensively before partitioning them. \nYes. Good shuffling of examples makes partitions much more likely to be statistically similar. \nSort the examples from earliest to most recent. \nIf the examples in the dataset are not stationary, then sorting makes the partitions *less* similar. \nDo nothing. Given enough examples, the law of averages naturally ensures that the distributions will be statistically similar. \nUnfortunately, this is not the case. The examples in certain sections of the dataset may differ from those in other sections. \nA streaming service is developing a model to predict the popularity of potential new television shows for the next three years. The streaming service plans to train the model on a dataset containing hundreds of millions of examples, spanning the previous ten years. Will this model encounter a problem? \nProbably. Viewers' tastes change in ways that past behavior can't predict. \nYes. Viewer tastes are not stationary. They constantly change. \nDefinitely not. The dataset is large enough to make good predictions. \nUnfortunately, viewers' tastes are nonstationary. \nProbably not. Viewers' tastes change in predictably cyclical ways. Ten years of data will enable the model to make good predictions on future trends. \nAlthough certain aspects of entertainment are somewhat cyclical, a model trained from past entertainment history will almost certainly have trouble making predictions about the next few years. \nA model aims to predict the time it takes for people to walk a mile based on weather data (temperature, dew point, and precipitation) collected over one year in a city whose weather varies significantly by season. Can you build and test a model from this dataset, even though the weather readings change dramatically by season? \nYes \nYes, it is possible to build and test a model from this dataset. You just have to ensure that the data is partitioned equally, so that data from all four seasons is distributed equally into the different partitions. \nNo \nAssuming this dataset contains enough examples of temperature, dew point, and precipitation, then you can build and test a model from this dataset. You just have to ensure that the data is partitioned equally, so that data from all four seasons is distributed equally into the different partitions.\n\n### Challenge exercise\n\nYou are creating a model that predicts the ideal date for riders to buy a\ntrain ticket for a particular route. For example, the model might recommend\nthat users buy their ticket on July 8 for a train that departs July 23.\nThe train company updates prices hourly, basing their updates on a variety\nof factors but mainly on the current number of available seats. That is:\n\n- If a lot of seats are available, ticket prices are typically low.\n- If very few seats are available, ticket prices are typically high.\n\nYour model exhibits low loss on the validation set and the test set but sometimes makes terrible predictions on real-world data. Why? \nClick here to see the answer \n**Answer:** The real world model is struggling with a\n**[feedback loop](/machine-learning/glossary#feedback-loop)**.\n\nFor example, suppose the model recommends that users buy tickets on July 8.\nSome riders who use the model's recommendation buy their tickets at 8:30\nin the morning on July 8. At 9:00, the train company raises prices because\nfewer seats are now available. Riders using the model's recommendation have\naltered prices. By evening, ticket prices might be much higher than in the\nmorning.\n| **Key terms:**\n|\n| - [Feedback loop](/machine-learning/glossary#feedback-loop)\n| - [Generalization](/machine-learning/glossary#generalization)\n| - [Generalization curve](/machine-learning/glossary#generalization-curve)\n| - [Independently and identically distributed (i.i.d)](/machine-learning/glossary#independently-and-identically-distributed-i.i.d)\n| - [Loss curve](/machine-learning/glossary#loss-curve)\n| - [Overfitting](/machine-learning/glossary#overfitting)\n| - [Stationarity](/machine-learning/glossary#stationarity)\n| - [Training set](/machine-learning/glossary#training-set)\n- [Underfitting](/machine-learning/glossary#underfitting) \n[Help Center](https://support.google.com/machinelearningeducation)"]]