상세 컨텐츠

본문 제목

37[머신러닝기초]Random Forest

로봇-AI

by happynaraepapa 2025. 1. 15. 10:26

본문

https://www.kaggle.com/code/dansbecker/random-forests

Random Forests

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com


Introduction
Decision trees leave you with a difficult decision. A deep tree with lots of leaves will overfit because each prediction is coming from historical data from only the few houses at its leaf. But a shallow tree with few leaves will perform poorly because it fails to capture as many distinctions in the raw data.
Decision Tree(이하 DT)에서,
Deep Tree (Depth가 깊다는 의미에서 이렇게 표현)의 경우에는 오버피팅이 낫고,  shallow tree(Depth가 얕다는 의미로)의 경우에는 언더피팅이 낫다.

Even today's most sophisticated modeling techniques face this tension between underfitting and overfitting. But, many models have clever ideas that can lead to better performance. We'll look at the random forest as an example
오늘날 최신의 가장 복잡한 모델링 테크닉을 쓰더라도 오버피팅과 언더피팅간의 적절한 균형을 찾는 것은 쉽지 않은 일이다. 그러나 많은 모델들이 적절한 성능을 낼 수 있는 혁신적인 방법을 제안해왔고 오늘 살펴볼 Random Forest (랜덤 포레스트, 이하 RF)도 그 중 하나다.

https://serokell.io/blog/random-forest-classification

The random forest uses many trees, and it makes a prediction by averaging the predictions of each component tree. It generally has much better predictive accuracy than a single decision tree and it works well with default parameters. If you keep modeling, you can learn more models with even better performance, but many of those are sensitive to getting the right parameters.
RF는 많은 트리를 사용하고 각 트리에서 나온 예측 값들의  평균을 가지고 예측한다. 이런 방법은 통상 한개의 트리만을 사용하는 방식과 비교해 훨씬 더 예측 정확도(predictive accuracy)가 높은 것으로 확인되며 기본 디폴트로 정해놓은 파라미터 상에서도 상대적으로 잘 작동된다.
앞으로 다양한 모델링 기법들을 접하게 되겠지만 대부분의 경우 파라미터 변화에 민감하다.


Example
예제

You've already seen the code to load the data a few times. At the end of data-loading, we have the following variables:
앞서 나온 예제대로 다시 자료를 로딩해보자.
>
train_X
val_X
train_y
val_y

We build a random forest model similarly to how we built a decision tree in scikit-learn - this time using the RandomForestRegressor class instead of DecisionTreeRegressor.
앞서 DT를 모델링할때와 아주 유사한 방식으로  사이킷런 패키지를 이용해서 RF 모델을 만들 거다.
>
#임포트하게될 라이브러리, 모듈
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error



forest_model = RandomForestRegressor(random_state=1)
forest_model.fit(train_X, train_y)

#RandomForestRegressor 라는 함수 선언이 있었고 전달된 인자는 random_state = 1 이다. 앞서 강의에 설명이 되었으니 이부분은 생략.
#근데 이걸 왜 forest_model에 지정 assign할까? 나중에 객체 지향(Object Oriented; )이나 클래스와 메서드 (Class and Method)의 개념을 이해하면 알게 된다. 여기서는 단순히 이 프로그램 내에서만 사용할 객체-인스탄스(Instance)를 생성하는 과정이라고 말해둔다. 클래스가 붕어빵틀이라면 이걸 이용해서 찍어낸 붕어빵이 인스탄스다. 지금 프로그램이 활동하려면 붕어빵을 먹여야 한다. 요렇게 이해하자.


melb_preds = forest_model.predict(val_X)


#melb_preds 는 멜번 지역 집값 예측하는 변수명
#여기에 앞서 만든 forest_model 의 predict메서드로 진행하고 거기에 val_X를 넣었다. val_X는 모델 평가(validate)하기 위한 X값 (feature값)들이었던거 알지?
#당연히 앞서 모델을 피팅할때 train_X, train_y 쓴 것도 앞서 DT를 할때와 동일한 거다.

print(mean_absolute_error(val_y, melb_preds))
#자 요건 뭘까?
#일단 mean_absolute_error는 앞서 배웠던 MAE에 대한 인스탄스이고, 인자로 실제값인 val_y와  melb_preds위에 구한 값을 넣는다.. 그래서 MAE를 구한다. - 그리고 그 값을 콘솔에 print해라는 명령.


Conclusion
There is likely room for further improvement, but this is a big improvement over the best decision tree error of 250,000. There are parameters which allow you to change the performance of the Random Forest much as we changed the maximum depth of the single decision tree. But one of the best features of Random Forest models is that they generally work reasonably even without this tuning.

앞서 DT 그리고 다양한 depth에 대한 모델 평가를 진행했을때, 가장 좋은 MAE값이 250,000이었다. 따라서 지금 위에서 구한 RF 모델의 MAE값이 크게 개선된 걸 알 수 있다. (물론 추가적인 개선 방법도 있겠지만.)

<끝>



관련글 더보기