[PYTHON] Kaggle House Prices ① ~ Feature Engineering ~

The following Kaggle competition feature engineering. House Prices: Advanced Regression Techniques

I refer to the following. Try to solve kaggle's House Prices [kaggle: House Price Tutorial](https://data-bunseki.com/2019/08/15/kaggle%EF%BC%9Ahouse-price-%E3%83%81%E3%83] % A5% E3% 83% BC% E3% 83% 88% E3% 83% AA% E3% 82% A2% E3% 83% AB% E4% BD% 8F% E5% AE% 85% E4% BE% A1 % E6% A0% BC% E3% 81% AE% E4% BA% 88% E6% B8% AC /)

Loading the library

import numpy as np
import pandas as pd
from sklearn.externals import joblib

Data reading

train = pd.read_csv('train.csv')
test_x = pd.read_csv('test.csv')

Exclude outliers

#Create a variable that totals the size of the property
train["TotalSF"] = train["1stFlrSF"] + train["2ndFlrSF"] + train["TotalBsmtSF"]
test_x["TotalSF"] = test_x["1stFlrSF"] + test_x["2ndFlrSF"] + test_x["TotalBsmtSF"]
#Exclude outliers
train = train.drop(train[(train['TotalSF']>7500) & (train['SalePrice']<300000)].index)
train = train.drop(train[(train['YearBuilt']<2000) & (train['SalePrice']>600000)].index)
train = train.drop(train[(train['OverallQual']<5) & (train['SalePrice']>200000)].index)
train = train.drop(train[(train['OverallQual']<10) & (train['SalePrice']>500000)].index)

Divide the training data into objective variables and others

train_x = train.drop('SalePrice',axis=1)
train_y = train["SalePrice"]

Integrate training data and test data

all_data = pd.concat([train_x,test_x],axis=0,sort=True)

The ID column is unnecessary, so store it in another variable

train_ID = train_x['Id']
test_ID = test_x['Id']

all_data.drop("Id", axis = 1, inplace = True)

Missing value correspondence

#List columns with missing values
na_col_list = all_data.isnull().sum()[all_data.isnull().sum()>0].index.tolist()

#Complementing missing values for adjacent road length (LotFrontage)
all_data['LotFrontage'] = all_data.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))

#Create a float type list with missing values
float_list = all_data[na_col_list].dtypes[all_data[na_col_list].dtypes == "float64"].index.tolist()

#Create a list of missing values and of type object
obj_list = all_data[na_col_list].dtypes[all_data[na_col_list].dtypes == "object"].index.tolist()

#For float type, replace the missing value with 0
all_data[float_list] = all_data[float_list].fillna(0)

#Missing value for object type"None"Replace with
all_data[obj_list] = all_data[obj_list].fillna("None")

Convert numeric variables to categorical variables

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

Addition of new features

#Create a variable that totals the size of the property
all_data["TotalSF"] = all_data["1stFlrSF"] + all_data["2ndFlrSF"] + all_data["TotalBsmtSF"]

#Added area per room to features
all_data["FeetPerRoom"] =  all_data["TotalSF"]/all_data["TotRmsAbvGrd"]

#Total of the year of construction and the year of remodeling
all_data['YearBuiltAndRemod']=all_data['YearBuilt']+all_data['YearRemodAdd']

#Total area of bathroom
all_data['Total_Bathrooms'] = (all_data['FullBath'] + (0.5 * all_data['HalfBath']) +
                               all_data['BsmtFullBath'] + (0.5 * all_data['BsmtHalfBath']))

#Total area on the porch
all_data['Total_porch_sf'] = (all_data['OpenPorchSF'] + all_data['3SsnPorch'] +
                              all_data['EnclosedPorch'] + all_data['ScreenPorch'] +
                              all_data['WoodDeckSF'])

#Presence or absence of pool
all_data['haspool'] = all_data['PoolArea'].apply(lambda x: 1 if x > 0 else 0)

#Presence or absence of the second floor
all_data['has2ndfloor'] = all_data['2ndFlrSF'].apply(lambda x: 1 if x > 0 else 0)

#With or without garage
all_data['hasgarage'] = all_data['GarageArea'].apply(lambda x: 1 if x > 0 else 0)

#Presence or absence of basement
all_data['hasbsmt'] = all_data['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)

#With or without fireplace
all_data['hasfireplace'] = all_data['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)

Do one-hot-encoding on categorical variables

#Extract columns that are categorical variables
cal_list = all_data.dtypes[all_data.dtypes=="object"].index.tolist()

#Get categorical variables_one by dummies-hot-Encode
all_data = pd.get_dummies(all_data,columns=cal_list)

Subdivided into training data and test data

train_x = all_data.iloc[:train_x.shape[0],:].reset_index(drop=True)
test_x = all_data.iloc[train_x.shape[0]:,:].reset_index(drop=True)

Save features

joblib.dump(train_x, 'train_x.pkl')
joblib.dump(test_x, 'test_x.pkl')
joblib.dump(train_y, 'train_y.pkl')

Recommended Posts

Kaggle House Prices ① ~ Feature Engineering ~
Challenge Kaggle [House Prices]
Kaggle House Prices ③ ~ Forecast / Submission ~
Challenge Kaggle [House Prices]
Kaggle House Prices ③ ~ Forecast / Submission ~
Supervised learning (regression) 2 Advanced edition
Kaggle House Prices ① ~ Feature Engineering ~
Kaggle: Introduction to Manual Feature Engineering Part 1
HJvanVeen's "Feature Engineering" Note
Kaggle ~ House Price Forecast ② ~
How to check for missing values (Kaggle: House Prices)
[Kaggle] Try Predict Future Engineering
Feature Engineering Traveling with Pokemon-Category Variables-
Feature Engineering Traveling with Pokemon-Numerical Edition-
Predicting Credit Card Defaults Feature Engineering
[Kaggle] I tried feature engineering of multidimensional time series data using tsfresh.