4. 1. 데이터 탐색
1) 각 변수에 대한 요약 및 설명
• 분석에 사용한 데이터는 Kaggle 에 공개된 “House Prices: Advanced Regression Techniques” 데이터셋이다.
• 이 자료는 미국 Ames와 Iowa에 위치한 주택 가격 정보를 포함하고 있다.
• 데이터는 2919개의 관측값 (Train: 1460, Test: 1459)과 80개의 변수로 이루어져 있다.
• 종속 변수는 주택 가격을 의미하는 SalePrice 이다.
SalePrice (1개) Numeric Variables (36개) Categorical Variables (43개)
종속변수
(Example)
• LotFrontage: Linear feet of street
connected to property
• OverallQual: Rates the overall material
and finish of the house
• YearBuilt: Original construction date
(Example)
• MSZoning: Identifies the general zoning classifica
tion of the sale.
A Agriculture
C Commercial
FV Floating Village Residential
I Industrial
RH Residential High Density
RL Residential Low Density
RP Residential Low Density Park
RM Residential Medium Density
6. 2. 데이터 전처리
1) 결측 값 처리
• 데이터의 결측값처리를 Categorical / Numeric 변수 타입에 따라 나누어 설명한다.
• Categorical 변수에 대한 결측값 처리 요약 테이블은 아래와 같다.
처리 방법 변수 리스트 비고
NA <- ”None”
FireplaceQu, GarageType, GarageFinish, GarageQual,
GarageCond, BsmtQual, BsmtCond, BsmtExposure,
BsmtFinType1, BsmtFinType2, MasVnrType
Data description 에 의거하여 처리
(Example)
GarageQual: Garage quality
Ex Excellent
Gd Good
TA Typical/Average
Fa Fair
Po Poor
NA No Garage
NA <- Mode(x)
MSZoning, Functional, Electrical, KitchenQual,
SaleType, Exterior1st, Exterior 2nd
위의 “None” 변환에 해당하지 않을 경우 해당 변수의 최
빈값 (mode)으로 대체
제거 PoolQC, MiscFeature, Alley, Fence NA 비율이 80% 이상이기 때문에 제거
Categorical Variable Missing Value Treatment
7. 2. 데이터 전처리
1) 결측 값 처리
• 데이터의 결측값처리를 Categorical / Numeric 변수 타입에 따라 나누어 설명한다.
• Continuous 타입 변수에 대한 결측값 처리 요약 테이블은 아래와 같다.
처리 방법 변수 리스트 비고
NA <- Median By
Group
LotFrontage, MasVnrArea, GarageArea
그룹 별로 분포가 다른 경우 그룹별 median으로 대체
• LotFrontage by Neighborhood
• MasVnrArea by MasVnrType
• GarageArea by GarageType
NA <- YearBuilt[x] GarageYrBlt
• GarageYrBlt와 YearBuilt 간 선형 관계 보이기 때문에 Yearbuilt값으로
대체 (GarageYrBlt 값이 2207년인 케이스 탐지, NA로 대체)
NA <- Median(x) GarageCars 그룹이 뚜렷하지 않은 경우 해당 변수의 median으로 대체
NA <- 0
BsmtFinSF1, BsmtFinSF2, BsmtUnfSF, TotalBsmtSF,
BsmtFullBath, BsmtHalfBath
다른 Bsmt 변수 BsmtQual, BsmtCond, BsmtExposure 이 “None”이기 때
문에 (NA가 있는 2121,2189 인덱스의) Bsmt 없다고 판단하여 0으로 대체
Numeric Variable Missing Value Treatment
8. 2. 데이터 전처리
1) 결측 값 처리
• Numeric 변수에 대한 Missing Value Imputation 근거 예시를 제공한다.
• GarageArea는 GarageType에 따라 다른 분포를 보인다
• GarageYrBlt는 YearBuilt와 선형 관계를 보인다
1900
1940
1980
1890 1920 1950 1980 2010
GarageYrBlt
YearBuilt
GarageYrBlt − YearBuilt
Boxplot(GarageArea ~GarageType) Scatterplot(GarageYrBlt ~YearBuilt)
0
500
1000
1500
2Types Attchd Basment BuiltIn CarPort Detchd None
GarageType
GarageArea
GarageType
2Types
Attchd
Basment
BuiltIn
CarPort
Detchd
None
GarageArea − GarageType
9. 2. 데이터 전처리
2) 변수 변환 (Variable Transformation)
• 변수의 타입을 변환한다
• Numeric 타입으로 지정되어 있지만 Categorical 이해하는게 더 합당한 경우
• Categorical 타입으로 지정되어 있지만 Ordinal로 생각하는게 합리적인 경우
Input Variable Transformation
처리 방법 변수 리스트 비고
Numeric => Categorical YrSold, MoSold, MSSubClass
명목형 변수의 특징을 가지는 변수 변환
• YrSold: 2006 ~ 2010 각 년도 마다 부동산 거래 상황 다를 수 있음
• MoSold: 1 ~ 12 각 월 마다 부동산 거래 상황 다를 수 있음
• MSSubClass: 주택 타입 나타냄 (e.g., 90: DUPLEX - ALL STYLES
AND AGES)
Categorical => Ordinal
FireplaceQu, BsmtQual, BsmtCond, GarageQual,
GarageCond, ExterQual, ExterCond, HeatingQC,
PoolQC, KitchenQual, BsmtFinType1, BsmtFinType2,
Functional, BsmtExposure, GarageFinish,
LandSlope, LotShape, PavedDrive, Street
우열 정보를 나타내는 경우 Ordinal 형태로 변환
(Example)
BsmtQual: Evaluates the height of the basement
Ex: Excellent (100-inches)
Gd: Good (90-99 inches)
TA: Typical (80-89 inches)
Fa: Fair (70-70)
Po: Poor (<90 inches)
NA: No Basement (“None”으로 변경되었음)
=> 5
=> 4
=> 3
=> 2
=> 1
=> 0
10. 2. 데이터 전처리
2) 변수 변환 (Variable Transformation)
• 종속변수 SalePrice 변환
• 정규성 가정 만족시키기 위해 Skewed된 분포를 log 연산을 통해 symmetric하게 변환
Output Variable Transformation
처리 방법 변수 리스트 비고
ln(y) SalePrice 정규성 만족시키기 위해 log 변환
0e+00
2e+05
4e+05
6e+05
−2 0 2
theoretical
sample
SalePrice
11
12
13
−2 0 2
theoretical
sample
SalePrice
Q-Q plot of SalePrice Q-Q plot of ln(SalePrice)
0
100
200
0e+00 2e+05 4e+05 6e+05
SalePrice
count
SalePrice
0
50
100
150
11 12 13
log(SalePrice)
count
SalePrice
Histogram of SalePrice Histogram of ln(SalePrice)
ln(y)
11. 2. 데이터 전처리
3) 변수 추가 (Adding New Features)
• 기존 변수의 정보를 이용해 새로운 변수 정의
• 변수 생성 방법은 아래와 같다
Adding New Features
추가된 변수 Equation 비고
TotBathrooms FullBath + 0.5*HalfBath + BsmtFullBath + 0.5*BsmtHalfBath
화장실 변수 통합
(*Combination에 사용한 변수들은 제거)
Remod
If (YearBuilt != YearRemodAdd), 1
Else, 0
YearBuilt와 YearRemodAdd 가 같은 경우
Remodeling이 이루어지지 않았음
IsNew
If (YearBuilt == YearSold), 1
Else, 0
YearBuilt와 YearSold가 같은 경우 거래 당시
신축 건물이라는 것을 알 수 있음
{
{
12. 2. 데이터 전처리
4) 비대칭 분포 변환 (Fixing Skewed Features)
• Numeric 타입 변수에 대해 Skewness 측정 (Ordinal, Categorical 변수 제외)
• Skewness의 절대값이 0.75보다 큰 변수 선택
• 해당 변수에 대해 BoxCox Transformation 적용
Fixing Skewed Features
처리 방법 변수 리스트 비고
BoxCox Transformation
LotFrontage, LotArea, MasVnrArea, BsmtFinSF1, BsmtFinSF2,
BsmtUnfSF, TotalBsmtSF, X1stFlrSF, X2ndFlrSF,
LowQualFinSF, GrLivArea, BedroomAbvGr, KitchenAbvGr, TotRmsAbvGrd
Fireplaces, GarageCars, GarageArea, WoodDeckSF, OpenPorchSF
EnclosedPorch, X3SsnPorch, ScreenPorch, PoolArea, MiscVal
Skewness의 절대값이 0.75보다 큰 Numeric
타입 변수들 변환
(오차의 정규성 가정 만족시키기 위해)
13. 2. 데이터 전처리
4) 비대칭 분포 변환 (Fixing Skewed Features)
• Skewed한 변수에 대한 BoxCox Transformation 예시
• BoxCox Transformation으로 skewed 분포가 symmetric하게 변환됐다
0
200
400
600
0 100 200 300
LotFrontage
count
LotFrontage
0
200
400
600
3 4 5
LotFrontage
count
LotFrontage
Histogram of LotFrontage Histogram of BoxCox(LotFrontage)
14. 2. 데이터 전처리
5) 상관계수가 큰 변수 제거 (Drop Highly Correlated Variables)
• Numeric과 Ordinal 타입의 변수들에 대한 correlation 측정
• Correlation의 절대값이 0.75보다 큰 pair 탐지
• 해당 pair에 속하는 변수 중 종속변수 (SalePrice)와의 correlation 절대값이 더 낮은 변수 제거
Drop Highly Correlated Variables
처리 방법 변수 리스트 Correlation Pair Abs(Correlation) 비고
제거
BsmtFinSF2 BsmtFinSF2 - BsmtFinType2 0.7992987
Correlation의 절대값이 0.75보다 큰
pair 중 종속변수 (SalePrice)와의
correlation 절대값이 낮은 변수 제거
X1stFlrSF X1stFlrSF - TotalBsmtSF 0.8013759
TotRmsAbvGrd TotRmsAbvGrd - GrLivArea 0.8083544
Fireplaces Fireplaces - FireplaceQu 0.8617354
GarageYrBlt GarageYrBlt - YearBuilt 0.8530176
GarageArea GarageArea - GarageCars 0.8896326
GarageCond GarageCond - GarageQual 0.9466563
15. 2. 데이터 전처리
6) 최종 데이터 형태
• 앞서 살펴본 전처리 과정을 통해 변형된 데이터 총 4개 생성
• 각 데이터셋에 동일한 모형 적합하여 데이터 전처리로 발생하는 변화 확인할 것
• (각 데이터셋의 categorical variable에 대해 dummify 작업. 이 때, reference category 제거)
순서 Missing Value Imputation Feature Engineering 변형된 데이터셋 이름 차원 크기
1 Rough X Rough_NoFeat 246
2 By Group X ByGroup_NoFeat 246
3 Rough O Rough_Feat 212
4 By Group O ByGroup_Feat 212
Candidate Datasets
17. 3. 모형 적합
1) 평가 측도 정의
• 모형의 비교를 위한 평가 측도 정의
• House Price 예측에 대해선 RMSE 사용
평가 측도
!"#$ %& = "#$ %& = $( %& − &
*
)
18. 3. 모형 적합
2) 모형 및 평가 방식 소개
• 적합에 사용된 모형은 3개
• 모형의 비교는 Train / Test 데이터로 진행 (튜닝이 필요한 모형은 5-fold CV 사용)
Model Description
모형 이름 모형 설명 튜닝 파라미터
LASSO Linear Regression with LASSO Lambda
RandFor Random Forest Mtry
XGB XGBoost Nrounds, max_depth, eta, gamma
전체 데이터를 고정된 인덱스
에 따라 5:5로 분할
50% (Training data) 로 모델
학습
(튜닝은 5-folds CV 사용)
50% (Test data)로 예측
in Kaggle
Model Fitting
19. 3. 모형 적합
3) Ensemble 방법 차용
• Ensemble 방법 2개 차용 (Simple Average와 Stacking 방식)
• 해당 방법에 대한 설명은 아래와 같다
Ensemble Description
모형 이름 모형 설명 비고
SimAvg Simple Average
LASSO, RF, XGB의 (Test set에 대한)
예측값 평균
Stack_LM Stacking by Linear Regression
LASSO, RF, XGB (Test set에 대한)
예측값을 input 변수로
받아 Linear Regression 적합
22. Model
RMSE
Rough_NoFeat ByGroup_NoFeat Rough Feat ByGroup_Feat
LASSO 0.13995 0.13985 0.13069 0.13064
RandFor 0.14857 0.14462 0.14117 0.14126
XGBoost 0.12570 0.12551 0.12429 0.12430
SimAvg 0.12560 0.12483 0.12454 0.12450
Stack_LM 0.12747 0.12721 0.12282 0.12277
4. 결과 요약
1) RMSE에 따른 모형 및 데이터 비교
• 각 열의 최댓값을 파란색 박스로 표시
• 모든 데이터 중 최댓값을 빨간색 박스로 표시
• MissingValue를 ByGroup으로 처리했을 때 그리고 FeatureEngineering 작업을 했을 때 전반적으로 결과가 좋아졌다