최적 트리 깊이 찾기
이제 결정 트리의 max_depth 파라미터를 튜닝해 과적합을 줄이면서도 모델 성능 지표를 잘 유지하는 값을 찾아보겠습니다. 여러 max_depth 후보 값을 for 루프로 순회하며 각 값에 대해 결정 트리를 학습하고, 이후 성능 지표를 계산할 거예요.
파라미터 후보가 들어 있는 depth_list는 미리 로드되어 있습니다. 2개 열로 구성된 depth_tuning 배열도 준비되어 있으며, 첫 번째 열에는 깊이 후보가 채워져 있고 두 번째 열은 재현율 점수를 위한 자리입니다. 또한 학습용 특성과 타깃은 train_X, train_Y, 테스트용은 test_X, test_Y로 로드되어 있어요. numpy와 pandas 라이브러리는 각각 np, pd로 불러와 두었습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 마케팅용 Machine Learning
연습 안내
- 리스트
depth_list의 길이까지 0부터 범위를 설정해for루프를 실행하세요. - 각 깊이 후보에 대해 결정 트리 분류기를 초기화하고 학습한 뒤, 테스트 데이터에서 이탈(churn)을 예측하세요.
- 각 깊이 후보에 대해
recall_score()함수를 사용해 재현율을 계산하고, 그 값을depth_tunning의 두 번째 열에 저장하세요. depth_tuning을 적절한 열 이름으로pandasDataFrame으로 만드세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Run a for loop over the range of depth list length
for index in ___(0, len(depth_list)):
# Initialize and fit decision tree with the `max_depth` candidate
mytree = DecisionTreeClassifier(___=depth_list[index])
mytree.fit(___, train_Y)
# Predict churn on the testing data
pred_test_Y = mytree.predict(___)
# Calculate the recall score
depth_tuning[index,1] = ___(test_Y, ___)
# Name the columns and print the array as pandas DataFrame
col_names = ['Max_Depth','Recall']
print(pd.DataFrame(depth_tuning, columns=___))