sources :
https://www.kaggle.com/code/dansbecker/underfitting-and-overfitting
Underfitting and Overfitting
Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources
www.kaggle.com
각 화면의 data tab을 클릭하면 해당회차에 쓰이는 데이터를 로컬로 다운받을 수 있다. 참고.
Experimenting With Different Models
다양한 비교군을 도입하는 방법
Now that you have a reliable way to measure model accuracy, you can experiment with alternative models and see which gives the best predictions. But what alternatives do you have for models?
여러 대안 모델을 교차 검증하여 최선의 모델을 찾을 수 있어야 하는데, 어떻게 대안 모델을 찾을 것인가?
You can see in scikit-learn's documentation that the decision tree model has many options (more than you'll want or need for a long time). The most important options determine the tree's depth. Recall from the first lesson in this course that a tree's depth is a measure of how many splits it makes before coming to a prediction.
decision tree 모델에 대한 공식 문건을 살펴보면 수많은 옵션이 가능한 데, 그 중 하나는 depth에 관한 것. (이전 강의를 기억하기 바라며 깊이는 몇단계로 나누느냐.)
In practice, it's not uncommon for a tree to have 10 splits between the top level (all
houses) and a leaf.
예제에서 2단계의 DT depth는 사실 너무 짧은 거고 실제로는 10단계 이상을 거쳐야 한다.
As the tree gets deeper, the dataset gets sliced up into leaves with fewer houses. If a tree only had 1 split, it divides the data into 2 groups. If each group is split again, we would get 4 groups of houses. Splitting each of those again would create 8 groups.
tree depth 가 깊어질수록 각 리프는 더 적은 수의 houses만을 갖는 조건으로 분화될 것.
...
If we keep doubling the number of groups by adding more splits at each level, we'll have
groups of houses by the time we get to the 10th level. That's 1024 leaves.
각 레벨에서 2의 승수로 분화됨을 고려하면 10th level에서 우리는 1024개의 분기(잎사귀;leaves)를 갖게 된다.
When we divide the houses amongst many leaves, we also have fewer houses in each leaf. Leaves with very few houses will make predictions that are quite close to those homes' actual values, but they may make very unreliable predictions for new data (because each prediction is based on only a few houses).
우리가 많은 분기를 만들수록 각 분기에 속하는 집의 숫자는 줄어들 것이고 세분화시키는 만큼 점점 더 예측 값은 실제값(집값)에 가까워져 갈 것이다. 하지만 이 모델을 기반으로 예측(Predict)했을때 상대적으로 적은 숫자의 집값 데이터를 근거로 하기 때문에 그 신뢰도가 높다고 보기 힘들다.
This is a phenomenon called overfitting, where a model matches the training data almost perfectly, but does poorly in validation and other new data. On the flip side, if we make our tree very shallow, it doesn't divide up the houses into very distinct groups.
계략적으로 설명했지만 이것이 오버피팅과 언더피팅의 개념이다.
현재 트레이닝 데이터를 거의 완벽하게 맞추도록 훈련을 시켰는데 이것에 새로운 데이터를 넣으면 결과가 안좋게 나오는데, 이것이 오버 피팅이 된 상황이고, 반대 상황으로 우리가 DT에서 depth 를 충분히 가져가지 않는다면 너무 계략적인 추정값이 나와서 다른 집값과 변별력이 없게 되고 결국 예측값 역시도 정확하지 않은 상황이 되는데 이것이 언더 피팅이다.
#이해하기 힘들 수 있다.
자 앞서 공부한 것을 떠올리면 우리는 주어진 학습 데이터를 모델에 넣어서 파라미터를 조정한다고 했다.
어떤 모델은 이 학습 데이터를 반복적으로 계속 집어 넣어서 그 파라미터를 거의 완벽<?> 하게 맞췄다고 해보자. 그런데 이 완벽함은 학습 데이터에게만 해당한다는 것이다. 만약 학습 데이터 외의 데이터를 predict 하기 위해 넣으면 지나치게 학습데이터에 맞게 조정된 파라미터 덕분에 오히려 다른 모델 보다도 부정확한 예측 값을 내놓게 되는 현상 이것이 오버 피팅 이다. 즉 과도한 피팅이 이루어졌다는 설명이다.
그리고 반대 경우가 언더 피팅이 되겠다.
At an extreme, if a tree divides houses into only 2 or 4, each group still has a wide variety of houses. Resulting predictions may be far off for most houses, even in the training data (and it will be bad in validation too for the same reason). When a model fails to capture important distinctions and patterns in the data, so it performs poorly even in training data, that is called underfitting.
예를 들어 극단적으로 집의 분류를 depth 2 ~4로 만 나누게 되면 각 분기 그룹은 여전히 많은 다양성을 내포한 집들을 가지고 있게 된다.
어떤 모델이 예측을 실현하기 위해 데이터 셋에서 발견해야할 패턴이나 중요한 차이점들 (파라미터든 뭐든) 캐치해 내지 못했다면 이 모델의 목적인 회귀든 분류든 효과적으로 달성하기 힘든 상황이 된다. 이러한 경우를 언더 피팅이라고 한다.
Since we care about accuracy on new data, which we estimate from our validation data, we want to find the sweet spot between underfitting and overfitting. Visually, we want the low point of the (red) validation curve in the figure below.
새로운 데이터에서의 예측 정확도(accuracy)를 고려한다면 바로 이 언더피팅과 오버피팅 사이의 절묘한 지점을 선택하는 것이 가장 좋을 것이다.
예를 들자면 아래 그림에서 red curve의 저점을 원하는 것이다.
underfitting_overfitting
언더피팅 오버 피팅
There are a few alternatives for controlling the tree depth, and many allow for some routes through the tree to have greater depth than other routes. But the max_leaf_nodes argument provides a very sensible way to control overfitting vs underfitting. The more leaves we allow the model to make, the more we move from the underfitting area in the above graph to the overfitting area.
tree depth를 조정하는 방법은 여러가지가 있고 그 중 하나는 max_leaf_nodes로 최대 depth값으로 컨트롤하는 방법이 있다. 하지만 이것은 언더 피팅이나 오버 피팅에 민감도가 높아서 조정하기 힘들다.
We can use a utility function to help compare MAE scores from different values for max_leaf_nodes:
우리는 유틸 함수로 max_leaf_nodes의 MAE(Mean Absolute Error: 오차의 절대값 평균)값을 구해서 비교할 것이다. #MAE에 대한 수학적 의미에 대해서 나중에 설명.
>>
#사이킷런 패키지 이용
#from 패키지 import 모듈 형식은 앞 이전에 알려줬고,
from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor
#아래는 get_mae라는 사용자 함수를 정의.
#여기에 DT의 최대 잎사귀 개수, 그리고 트레이닝 데이터인 train_X, train_Y, 검증데이터인 val_X, val_Y를 인자로 전달하도록 정의됨. 참고로 이 (X, Y)의 데이터는 (당연히) 실제 조사된 데이터 셋에서 받아온 값이다.
#참고로 train_X는 트레이닝 데이터라는 의미로 X는 앞서 설명한 feature들의 값 Y는 집값으로 보면 되고, val_X는 validate 검증 데이터를 집어 넣는 것으로 보면 됨.
#현재로서는 아래 코드를 모두 이해하기 힘들고 틀을 외운다는 형태로 접근한 뒤 차차 이해하는 것이 좋겠다.
def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
#DecisionTreeRegressor는 모델을 선언하고 .
model.fit(train_X, train_y)
#피팅을 해주고
preds_val = model.predict(val_X)
#모델에서 예측값 prediction ㅐ주고
mae = mean_absolute_error(val_y, preds_val)
#자 실제값과 예측값을 이용해서 MAE를 구하는 것.
#대충 감이 오겠지만 val_y는 데이터 셋의 실제 값이고 preds_val은 예측치니까 둘 사이에 오차가 적을 수록 모델이 정확하다는 의미일 것이다. 즉 MAE가 적을 수록 모델이 잘 맞는다는 것.
return(mae)
#MAE값을 돌려준다.
The data is loaded into train_X, val_X, train_y and val_y using the code you've already seen (and which you've already written)
train_X.... val_y까지 데이터값을 올리는 방법은 앞서 데이터셋을 다루는 방법을 배울때 익혔던 코드를 사용하면 된다.
We can use a for-loop to compare the accuracy of models built with different values for max_leaf_nodes.
여기에 for 문을 더해서 각기 다른 max_leaf_nodes에 따라서 모델의 정확도(accuracy)를 나타내는 MAE가 어떻게 변화하는지 볼 수 있다.
...(이하 생략)..
Conclusion
Here's the takeaway: Models can suffer from either:
모든 모델은 오버피팅이나 언더 피팅에 영향을 받는다. (적절한 위치를 찾아야 한다.)
Overfitting: capturing spurious patterns that won't recur in the future, leading to less accurate predictions, or
Underfitting: failing to capture relevant patterns, again leading to less accurate predictions.
We use validation data, which isn't used in model training, to measure a candidate model's accuracy. This lets us try many candidate models and keep the best one.
#앞서 했던 말 반복이라 추가로 적지 않겠다. 위 내용은 스스로 이해해 보라.
<끝>
[머신러닝기초] Machine Learning Competitions (0) | 2025.01.16 |
---|---|
37[머신러닝기초]Random Forest (0) | 2025.01.15 |
[머신러닝 기초] Your First ML Model (0) | 2025.01.10 |
[머신러닝기초]Basic Data Exploration (0) | 2025.01.08 |
[머신러닝기초] How Models Work (0) | 2025.01.08 |