본문 바로가기
캐글(Kaggle)/프로젝트

Kaggle(캐글) - 주택 가격 예측 초보자 튜토리얼[Hellfer](3)

by Hellfer 2024. 7. 8.
728x90

https://www.kaggle.com/code/jimmyyeung/house-regression-beginner-catboost-top-2/notebook

 

🔥House Regression: Beginner Catboost (Top 2%)🚀

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

www.kaggle.com

 

위의 글을 보고 참고하여 작성하였습니다.

 

데이터 전처리 (Data Preprocessing)는 데이터를 분석하거나 모델링에 사용하기 전에 데이터를 정리하고 변환하는 과정입니다.

 

1. 데이터 수집

- 웹 스크래핑

- API 활용

- 데이터베이스 쿼리

 

2. 데이터 정제

- 결측값 처리 : 평균, 중위수, 최빈값 대체, 삭제

- 중복 데이터 제거 : 중복 행 제거, 고유 식별자 사용

- 이상치 탐지 및 제거 : IQR, Z-score, 시각화

 

3. 데이터 변환

- 스케일링 : Min-Max 스케일링, 정규화

- 정규화 : L1, L2 정규화

- 범주형 데이터 인코딩 : 원 - 핫 인코딩, 라벨 인코딩, 순서형 인코딩

 

4. 데이터 통합

 

5. 데이터 축소

- 차원 축소 기법 : 주성분 분석(PCA), 선형 판별 분석(LDA), t-SNE

- 특징 선택 : 필터 방식, 래퍼 방식, 임베디드 방식

 

 


 

 

train_test 데이터프레임의 'MSSubClass',  'YrSold', 'MoSold', 열의 데이터 타입을 문자열로 변환합니다.

 

범주형 변수를 숫자형에서 문자열로 변환합니다.

 

train_test['MSSubClass'] = train_test['MSSubClass'].apply(str)
train_test['YrSold'] = train_test['YrSold'].apply(str)
train_test['MoSold'] = train_test['MoSold'].apply(str)

 

 

train_test 데이터프레임의 결측치를 채우는 작업을 수행합니다.

 

train_test['Functional'] = train_test['Functional'].fillna('Typ')
train_test['Electrical'] = train_test['Electrical'].fillna("SBrkr")
train_test['KitchenQual'] = train_test['KitchenQual'].fillna("TA")
train_test['Exterior1st'] = train_test['Exterior1st'].fillna(train_test['Exterior1st'].mode()[0])
train_test['Exterior2nd'] = train_test['Exterior2nd'].fillna(train_test['Exterior2nd'].mode()[0])
train_test['SaleType'] = train_test['SaleType'].fillna(train_test['SaleType'].mode()[0])
train_test["PoolQC"] = train_test["PoolQC"].fillna("None")
train_test["Alley"] = train_test["Alley"].fillna("None")
train_test['FireplaceQu'] = train_test['FireplaceQu'].fillna("None")
train_test['Fence'] = train_test['Fence'].fillna("None")
train_test['MiscFeature'] = train_test['MiscFeature'].fillna("None")

for col in ('GarageArea', 'GarageCars'):
    train_test[col] = train_test[col].fillna(0)
        
for col in ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']:
    train_test[col] = train_test[col].fillna('None')
    
for col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):
    train_test[col] = train_test[col].fillna('None')

 

 

train_test 데이터프레임에서 'GarageYrBlt''YearRemodAdd'을 제거합니다.

 

useless = ['GarageYrBlt', 'YearRemodAdd']
train_test.drop(useless, axis=1, inplace=True)

 

 

train_test 데이터프레임에서 결측치가 있는 열을 찾아내어 리스트로 반환합니다.

 

# 결측치 개수를 계산
missing_value = train_test.isnull().sum()
# 결측치 개수가 0보다 큰 열들의 이름을 리스트로 추출
columns_with_missing = missing_value[missing_value > 0].index.tolist()

columns_with_missing = [col for col in columns_with_missing if train_test[col].isnull().any()]

print('Columns with missing values:', columns_with_missing)

 

 

Columns with missing values: ['MSZoning', 'LotFrontage', 'Utilities', 'YearRemod/Add', 'MasVnrType', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath', 'SalePrice']

 

 

 


 

 

K - 최근접 이웃 (K-Nearest Neighbors, KNN) 회귀 모델은 주어진 데이터 포인트에 대한 예측을 가장 가까운 K개의 이웃 데이터 포인트의 값을 기반으로 수행하는 비모수 회귀 방법입니다.

 

1. 거리 계산

- 예측하고자 하는 새로운 데이터와 기존 데이터 포인트 간의 거리를 계산합니다.

- 일반적으로 유클리드 거리를 사용하지만, 다른 거리 척도도 사용할 수 있습니다.

 

2. K개의 이웃 선택 

- 계산된 거리들을 기준으로 가장 가까운 K개의 이웃을 선택하고 K는 사용자가 직접 정하는 하이퍼파라미터입니다.

 

3. 평균 계산

- 선택된 K개의 이웃의 목표 변수 값(종속 변수 값)의 평균을 계산하여 새로운 데이터의 포인트 값을 예측합니다.

 

def impute_knn(df):
    # 숫자형 데이터와 비숫자형 데이터의 분리
    ttn = train_test.select_dtypes(include=[np.number])
    ttc = train_test.select_dtypes(exclude=[np.number])
    
    # 결측치가 있는 열과 없는 열로 분리하여 리스트로 저장
    cols_nan = ttn.columns[ttn.isna().any()].tolist()   
    cols_no_nan = ttn.columns.difference(cols_nan).values 
    
    #KNN 회귀 모델을 사용한 결측치 대체 
    for col in cols_nan:
        imp_test = ttn[ttn[col].isna()] 
        imp_train = ttn.dropna()
        model = KNeighborsRegressor(n_neighbors=5)
        knr = model.fit(imp_train[cols_no_nan], imp_train[col])
        ttn.loc[ttn[col].isna(), col] = knr.predict(imp_test[cols_no_nan])
    
    return pd.concat([ttn, ttc],axis=1)

train_test = impute_knn(train_test)

 

 

train_test 데이터프레임에서 데이터 타입이 object인 열들을 찾아서, 해당 열에서 결측값을 'None'으로 채우고, 결측값의 개수를 출력합니다.

 

# 빈 리스트 생성
objects = []
# 데이터셋을 순회하면서 타입이 object면 리스트에 추가
for i in train_test.columns:
    if train_test[i].dtype == object:
        objects.append(i)

# 데이터 타입이 object인 결측값을 None으로 대체
train_test.update(train_test[objects].fillna('None'))
# 결측값이 있는 열들의 개수를 출력
train_test[columns_with_missing].isna().sum()

 

MSZoning         0
LotFrontage      0
Utilities        0
YearRemod/Add    0
MasVnrType       0
MasVnrArea       0
BsmtFinSF1       0
BsmtFinSF2       0
BsmtUnfSF        0
TotalBsmtSF      0
BsmtFullBath     0
BsmtHalfBath     0
SalePrice        0
dtype: int64

 

 


 

train_test에 여러 가지 새로운 변수를 추가합니다.

 

1. SqFtPerRoom

- 주거 면적(GrLivArea)을 방의 총 수(TotRmsAbvGrd), 전체 욕실(FullBath), 반 욕실(HalfBath), 주방 수(KitchenAbvGr)의 합으로 나눈 값입니다.

 

train_test["SqFtPerRoom"] = train_test["GrLivArea"] / (train_test["TotRmsAbvGrd"] +
                                                       train_test["FullBath"] +
                                                       train_test["HalfBath"] +
                                                       train_test["KitchenAbvGr"])

 

 

2. Total_Home_Quality

- 주택의 전반적인 품질(OverallQual)과 상태(OverallCond)의 합입니다.

 

train_test['Total_Home_Quality'] = train_test['OverallQual'] + train_test['OverallCond']

 

 

3. Total_Bathrooms

- 전체 욕실 수를 계산합니다.

전체 욕실(FullBath), 반 욕실(HalfBath)의 절반, 지하 전체 욕실(BsmtFullBath), 지하 반 욕실(BsmtHalfBath)의 절반을 더한 값입니다.

 

train_test['Total_Bathrooms'] = (train_test['FullBath'] + (0.5 * train_test['HalfBath']) +
                               train_test['BsmtFullBath'] + (0.5 * train_test['BsmtHalfBath']))

 

 

4. HighQualSF

- 주거 면적(GrLivArea), 1층 면적(1 stFlrSF), 2층 면적(2 ndFlrSF), 차고 면적(GarageArea)의 절반, 지하실 총면적(TotalBsmtSF)의 절반, 벽돌 외장 면적(MasVnrArea)의 합입니다.

 

train_test["HighQualSF"] = train_test["GrLivArea"] + train_test["1stFlrSF"] + train_test["2ndFlrSF"] + 0.5 * train_test["GarageArea"] + 0.5 * train_test["TotalBsmtSF"] + 1 * train_test["MasVnrArea"]

 

 

5. Age

- 주택의 연식을 계산합니다. 판매 연도(YrSold)에서 건축 연도(YearBuilt)를 뺀 값입니다.

 

train_test["Age"] = pd.to_numeric(train_test["YrSold"]) - pd.to_numeric(train_test["YearBuilt"])

 

 

6. Renovate

- 리모델링 여부를 계산합니다. 리모델링 또는 추가된 연도(YearRemod/Add)에서 건축 연도(YearBuilt)를 뺀 값입니다.

 

train_test["Renovate"] = pd.to_numeric(train_test["YearRemod/Add"]) - pd.to_numeric(train_test["YearBuilt"])

 

 

 

728x90