<jupyter_start><jupyter_text>Model Selection using RFE (Housing Case Study)  Importing and Understanding Data<jupyter_code># Supress Warnings

import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
# Importing Housing.csv
housing = pd.read_csv('Housing.csv')
# Looking at the first five rows
housing.head()<jupyter_output><empty_output><jupyter_text>Data Preparation<jupyter_code># List of variables to map

varlist =  ['mainroad', 'guestroom', 'basement', 'hotwaterheating', 'airconditioning', 'prefarea']

# Defining the map function
def binary_map(x):
    return x.map({'yes': 1, "no": 0})

# Applying the function to the housing list
housing[varlist] = housing[varlist].apply(binary_map)
# Check the housing dataframe now

housing.head()<jupyter_output><empty_output><jupyter_text>Dummy Variables The variable `furnishingstatus` has three levels. We need to convert these levels into integer as well. For this, we will use something called `dummy variables`.<jupyter_code># Get the dummy variables for the feature 'furnishingstatus' and store it in a new variable - 'status'

status = pd.get_dummies(housing['furnishingstatus'])

# Check what the dataset 'status' looks like
status.head()<jupyter_output><empty_output><jupyter_text>Now, you don't need three columns. You can drop the `furnished` column, as the type of furnishing can be identified with just the last two columns where — - `00` will correspond to `furnished`- `01` will correspond to `unfurnished`- `10` will correspond to `semi-furnished`<jupyter_code># Let's drop the first column from status df using 'drop_first = True'
status = pd.get_dummies(housing['furnishingstatus'], drop_first = True)

# Add the results to the original housing dataframe
housing = pd.concat([housing, status], axis = 1)

# Now let's see the head of our dataframe.
housing.head()
# Drop 'furnishingstatus' as we have created the dummies for it
housing.drop(['furnishingstatus'], axis = 1, inplace = True)

housing.head()<jupyter_output><empty_output><jupyter_text>Splitting the Data into Training and Testing Sets<jupyter_code>from sklearn.model_selection import train_test_split

# We specify this so that the train and test data set always have the same rows, respectively

df_train, df_test = train_test_split(housing, train_size = 0.7, test_size = 0.3, random_state = 100)<jupyter_output><empty_output><jupyter_text>Rescaling the Features We will use MinMax scaling.<jupyter_code>from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
# Apply scaler() to all the columns except the 'yes-no' and 'dummy' variables
num_vars = ['area', 'bedrooms', 'bathrooms', 'stories', 'parking','price']

df_train[num_vars] = scaler.fit_transform(df_train[num_vars])

df_train.head()<jupyter_output><empty_output><jupyter_text>Dividing into X and Y sets for the model building<jupyter_code>y_train = df_train.pop('price')
X_train = df_train<jupyter_output><empty_output><jupyter_text>Building our modelThis time, we will be using the **LinearRegression function from SciKit Learn** for its compatibility with RFE (which is a utility from sklearn)  RFERecursive feature elimination<jupyter_code># Importing RFE and LinearRegression
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
# Running RFE with the output number of the variable equal to 10
lm = LinearRegression()
lm.fit(X_train, y_train)

rfe = RFE(lm, 10)             # running RFE
rfe = rfe.fit(X_train, y_train)
list(zip(X_train.columns,rfe.support_,rfe.ranking_))
col = X_train.columns[rfe.support_]
col
X_train.columns[~rfe.support_]<jupyter_output><empty_output><jupyter_text>Building model using statsmodel, for the detailed statistics<jupyter_code># Creating X_test dataframe with RFE selected variables
X_train_rfe = X_train[col]
# Adding a constant variable 
import statsmodels.api as sm  
X_train_rfe = sm.add_constant(X_train_rfe)
lm = sm.OLS(y_train,X_train_rfe).fit()   # Running the linear model
#Let's see the summary of our linear model
print(lm.summary())<jupyter_output>OLS Regression Results                            
==============================================================================
Dep. Variable:                  price   R-squared:                       0.669
Model:                            OLS   Adj. R-squared:                  0.660
Method:                 Least Squares   F-statistic:                     74.89
Date:                Tue, 09 Oct 2018   Prob (F-statistic):           1.28e-82
Time:                        13:15:31   Log-Likelihood:                 374.65
No. Observations:                 381   AIC:                            -727.3
Df Residuals:                     370   BIC:                            -683.9
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
===================================================================================
                      coef    std err          [...]<jupyter_text>`Bedrooms` is insignificant in presence of other variables; can be dropped<jupyter_code>X_train_new = X_train_rfe.drop(["bedrooms"], axis = 1)<jupyter_output><empty_output><jupyter_text>Rebuilding the model without `bedrooms`<jupyter_code># Adding a constant variable 
import statsmodels.api as sm  
X_train_lm = sm.add_constant(X_train_new)
lm = sm.OLS(y_train,X_train_lm).fit()   # Running the linear model
#Let's see the summary of our linear model
print(lm.summary())
X_train_new.columns
X_train_new = X_train_new.drop(['const'], axis=1)
# Calculate the VIFs for the new model
from statsmodels.stats.outliers_influence import variance_inflation_factor

vif = pd.DataFrame()
X = X_train_new
vif['Features'] = X.columns
vif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif<jupyter_output><empty_output><jupyter_text>Residual Analysis of the train dataSo, now to check if the error terms are also normally distributed (which is infact, one of the major assumptions of linear regression), let us plot the histogram of the error terms and see what it looks like.<jupyter_code>y_train_price = lm.predict(X_train_lm)
# Importing the required libraries for plots.
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# Plot the histogram of the error terms
fig = plt.figure()
sns.distplot((y_train - y_train_price), bins = 20)
fig.suptitle('Error Terms', fontsize = 20)                  # Plot heading 
plt.xlabel('Errors', fontsize = 18)                         # X-label<jupyter_output>C:\Users\admin\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
  warnings.warn("The 'normed' kwarg is deprecated, and has been "<jupyter_text>Making Predictions  Applying the scaling on the test sets<jupyter_code>num_vars = ['area', 'bedrooms', 'bathrooms', 'stories', 'parking','price']

df_test[num_vars] = scaler.transform(df_test[num_vars])<jupyter_output><empty_output><jupyter_text>Dividing into X_test and y_test<jupyter_code>y_test = df_test.pop('price')
X_test = df_test
# Now let's use our model to make predictions.

# Creating X_test_new dataframe by dropping variables from X_test
X_test_new = X_test[X_train_new.columns]

# Adding a constant variable 
X_test_new = sm.add_constant(X_test_new)
# Making predictions
y_pred = lm.predict(X_test_new)<jupyter_output><empty_output><jupyter_text>Model Evaluation<jupyter_code># Plotting y_test and y_pred to understand the spread.
fig = plt.figure()
plt.scatter(y_test,y_pred)
fig.suptitle('y_test vs y_pred', fontsize=20)              # Plot heading 
plt.xlabel('y_test', fontsize=18)                          # X-label
plt.ylabel('y_pred', fontsize=16)                          # Y-label<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.111961842600728, 'fraction_numerical': 0.011547633990209614, 'mean_word_length': 4.137330754352031, 'pattern_counts': {'":': 1, '<': 59, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '49101', 'license': 'MIT', 'n_tokens_mistral': 2618, 'n_tokens_neox': 2479, 'n_words': 718, 'path': 'Housing+Case+Study+using+RFE.ipynb', 'repo_name': 'krupabdhi/predicting-house-price-RFE', 'size': '7967'}