<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kamski John on Medium]]></title>
        <description><![CDATA[Stories by Kamski John on Medium]]></description>
        <link>https://medium.com/@kamskijohnm2m?source=rss-4824483b679a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wuS7Up9PU_PBTfRi82tN-g.jpeg</url>
            <title>Stories by Kamski John on Medium</title>
            <link>https://medium.com/@kamskijohnm2m?source=rss-4824483b679a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:00:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamskijohnm2m/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ames Housing Price Prediction — Complete ML Project with Python]]></title>
            <link>https://medium.com/@kamskijohnm2m/ames-housing-price-prediction-complete-ml-project-with-python-2af595a749d6?source=rss-4824483b679a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2af595a749d6</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Kamski John]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 16:34:34 GMT</pubDate>
            <atom:updated>2019-04-02T16:33:55.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ames Housing Price Prediction — Complete ML Project with Python</h3><blockquote>Simple Exploratory Data analysis and Data pre-processing</blockquote><p>Hello everyone. I was recently learning about Exploratory Data Analysis (EDA) and Data pre-processing and thought that it will be worth sharing what I’ve learned so far. I will be using Ames housing dataset from Kaggle here. This is just my second Kaggle Project and I am still learning and learning….. So suggestions and comments are more than welcome!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkhefdsEERZdbn1kOcuPcQ.jpeg" /><figcaption>I’ve no idea, why i placed this image here. So dont ask.</figcaption></figure><p>I will be using python throughout the project and will concentrate more on EDA and Data pre-processing than modelling. Let’s begin by understanding the problem. The dataset consists of 79 features almost describing everything that makes a house (even things that we never really care about) and the task is to predict the <em>SalePrice </em>of a house.</p><h3><strong>Understanding the data</strong></h3><p>Let me first import libraries and the dataset.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import warnings<br>warnings.filterwarnings(‘ignore’)<br>pd.set_option(‘display.max_rows’, 500)<br>pd.set_option(‘display.max_columns’, 500)<br>plt.style.use(‘fivethirtyeight’)<br>from scipy import stats<br>%matplotlib inline</pre><pre>train = pd.read_csv(‘../MyPC/Ames/train.csv’)<br>test = pd.read_csv(‘../MyPC/Ames/test.csv’)</pre><p>The best way to begin any ML project is by understanding the data. The better we understand the data, the more we can use it to help ourselves in manipulating it to make better predictions. So let’s look at the available features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gnjk1dKfULEpN30U6D2blQ.png" /></figure><p>There is hell of a lot of features present and we’ll deal with them. There is information about the various Area’s, Land and Location, Types of finishing, Basement, Garage, Year, Pool, additional facilities etc… Most people would consider the location of the house, No. of bedrooms, Year the house is built as the primary factors when looking for a new house. But as it turns out, this dataset proves that factors like basement area, garage size etc… influence the price more than the former ones.</p><p><strong>The Target variable SalePrice:</strong></p><p>The most important variable here is the target variable <em>SalePrice. Let’s check its distribution.</em></p><pre>sns.distplot(train.SalePrice)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*DSpOXDOdort1hpujWgp2Rg.png" /></figure><p>This shows that <em>SalePrice </em>does not follow normal distribution<em>.</em> It has positive skewness<em>. </em>It shows that very small number of houses have very high <em>SalePrice.</em> Also the SalePrice is not linear, which means we cannot find of a straight line that would fit through the <em>SalePrice </em>data. So we have to transform<em> SalePrice so </em>that it’ll have normal distribution.</p><p>The most important thing any statistics class will teach you is that log transformation works fine with positive skewness. So lets take log for <em>SalePrice</em>.</p><pre>figure = plt.figure(figsize = (13,5))<br>plt.subplot(1,2,1)<br>stats.probplot(train.SalePrice, plot = plt)<br>plt.title(‘Actual SalePrice’)<br>plt.subplot(1,2,2)<br>train.SalePrice = np.log(train.SalePrice)<br>stats.probplot(train.SalePrice, plot = plt)<br>plt.title(‘SalePrice after log transformation’)<br>plt.show()<br>plt.savefig(‘SalePrice.jpg’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*0k7X6YCJgyG9V8wf6qvG2w.png" /></figure><h3>Looking for missing values</h3><p>I like to first look for missing values and deal with them. The training set has a total of 1460 samples.</p><pre>missing = train.isna().sum()<br>missing = missing[missing&gt;0]<br>missing_perc = missing/train.shape[0]*100<br>na = pd.DataFrame([missing, missing_perc], index = [‘missing_num’, ‘missing_perc’]).T<br>na = na.sort_values(by = ‘missing_perc’, ascending = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*b_0gQK2gI_EhUwhpdkqv2A.png" /></figure><p>So we have missing values in 19 columns. We can choose to fill them with appropriate values or we can drop particular rows (samples) or the the entire columns with missing values.</p><p>There are even features with more than 90% missing values. That is because most houses do not have a Pool, Misc feature, no Alley associated with them etc... I am going to completely drop all those features except <em>GarageQual, GarageCond, BsmtCond, BsmtQual, LotFrontage, MasVnrArea and Electrical.</em> I can drop of these variables, as they don’t seem to have an influence on the sale price. Also most of them are collinear with other available features. I trained the same model by including these features and again after dropping them. I didn’t any considerable difference in the result. And i am going to drop just the one sample with missing<em> Electrical </em>value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*jBd2Pz1SAqcrSyQmaZKjqw.png" /></figure><p>For the remaining 6 features as i looked at the data, i can see that <em>GarageQual, GarageCond, BsmtCond, BsmtQual </em>are missing in houses that do not have a garage or a basement. So i am going to fill them with<em> ‘NA’</em> which is the default value if the feature is not present. And missing values in <em>LotFrontage and MasVnrArea </em>can be replaced by zero.</p><pre>train.drop([‘PoolQC’, ‘MiscFeature’, ‘Alley’, ‘Fence’, ‘FireplaceQu’,<br> ‘LotFrontage’, ‘GarageType’, ‘GarageYrBlt’, <br> ‘GarageFinish’,’BsmtExposure’, ‘BsmtFinType2’, ‘BsmtFinType1’,<br> ‘MasVnrArea’, ‘MasVnrType’], axis = 1, inplace = True)</pre><pre>train.drop(train[train.Electrical.isna()].index, axis = 0, inplace = True)<br>NA = [ ‘GarageQual’, ‘GarageCond’, ‘BsmtCond’, ‘BsmtQual’]<br>for na in NA:<br> train[na].fillna(‘NA’, inplace = True)<br>train[&#39;MasVnrArea&#39;].fillna(0, inplace = True)<br>train[&#39;LotFrontage&#39;].fillna(0, inplace = True)</pre><h3><strong>Understanding the Correlations</strong></h3><p>To know what are features that have the most influence on the <em>SalePrice</em>, lets plot the correlation. It is also good to check whether independent features are correlated among themselves, which will result in <a href="https://en.wikipedia.org/wiki/Multicollinearity">Multicollinearity</a>.</p><pre>plt.figure(figsize = (15,10))<br>sns.heatmap(train.corr(), vmax=.8, square=True)<br>plt.savefig(‘C:\\Users\\MyPC\\Pictures\\Heatmap.jpg’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*JiY2fLnSQFhvkAipb9npUg.png" /></figure><p>So the heatmap shows that <strong>Overall quality</strong> and <strong>Ground Living Area </strong>have the highest correlation with the <em>SalePrice</em>. It is obvious because larger houses will definitely be costlier than smaller ones and though it is not clear on what basis <em>OverallQual </em>is calculated, <em>SalePrice </em>will be proportional to quality.</p><p>And other features with considerable correlations with <em>SalePrice </em>are <em>TotalBsmtSF, 1stFlrSurface, FullBath, GarageCars and GarageArea,</em> which also makes sense.</p><p>Also we can see some high correlation within the independent variables. There is high correlation between <em>GrLivArea </em>and <em>TotRmsAbvGrd </em>and similar relation<em> </em>exists between <em>GarageCars </em>and <em>GarageArea. </em>This will lead to multicollinearity and the our linear model may struggle to identify the relationship between these features and <em>SalePrice. </em>So it is recommended to drop one of those features.</p><p>To confirm all these correlations, lets plot the scatter plot for these features.</p><pre>plt.figure(figsize = (11,4))<br>plt.subplot(1,2,1)<br>plt.scatter(train.OverallQual, train.SalePrice)<br>plt.xlabel(‘OverallQual’); plt.ylabel(‘Sale Price’)<br>plt.subplot(1,2,2)<br>plt.scatter(train.GrLivArea, train.SalePrice)<br>plt.xlabel(‘Grnd Living Area’); plt.ylabel(‘Sale Price’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*5FJ6wa5ld3Usk-wBzKnr8A.png" /></figure><p>The scatter plot confirms the high correlation between <em>GrLivArea, OverallQual </em>and <em>SalePrice. </em>Though we can see some outliers in the <em>GrndLivArea</em>, we’ll deal with it later. Ignore them for now.</p><p>Similarly, plot for <em>TotalBsmtSF, 1stFlrSurface, FullBath, GarageCars and GarageArea.</em></p><pre>var = [‘GarageCars’, ‘GarageArea’, ‘TotalBsmtSF’, ‘1stFlrSF’, ‘FullBath’]<br>sns.pairplot(x_vars = var, y_vars = ‘SalePrice’, data = train)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*_g5syDg6gahG-doD4LMRGw.png" /></figure><p>All these features show positive correlation with <em>SalePrice</em>.</p><h3>Feature Engineering</h3><p>Having understood the correlations in the features, let’s do some feature engineering to make our data better for modelling.</p><p>So first let’s solve the multicollinearity issue. So i am going to drop the <em>TotRmsAbvGrd</em>, and <em>GarageArea </em>features as they have less correlation with the <em>SalePrice </em>compared to <em>GarageCars </em>and GrLivArea<em>. </em>Also drop the <em>Id</em> column.</p><pre>train.drop(‘Id’, axis = 1, inplace = True)<br>train.drop([‘TotRmsAbvGrd’, ‘GarageArea’], axis =1, inplace = True)</pre><p>Now we can think about adding new features to the dataset. As <em>OverallQual, GrLivArea </em>have high correlation with <em>SalePrice</em>, creating features that are just the higher powers of <em>OverallQual and GrLivArea will help the model.</em></p><pre>features = [‘OverallQual’, ‘GrLivArea’]<br>for feat in features:<br> train[feat+’_p2&#39;] = train[feat] **2<br> train[feat+’_p3&#39;] = train[feat] **3</pre><p><strong>Dealing with categorical features</strong></p><p>Before doing further feature engineering, have to do look at our dataset again. We have both categorical and numerical features. But most ML models are only happy with numerical values. So we have to convert the categories into numbers. Also we have to be aware of he ordinal values (Categories in which order matters). So first let us convert the ordinal features to numerical based on their weight. For example Garage quality has the categories Ex, Gd, TA, Fa, Po, NA. So we have to convert this to numbers. But we have to be be aware that <em>‘Ex’ </em>refers to a higher quality and ‘<em>Po’ </em>refers to a lower quality. So encoding should be based on this.</p><pre>mp = {‘Ex’: 5, ‘Gd’:4, ‘TA’:3, ‘Fa’:2, ‘Po’:1, ‘NA’:0}<br>for feat in [‘ExterQual’, ‘ExterCond’, ‘BsmtQual’, ‘BsmtCond’,<br> ‘HeatingQC’, ‘KitchenQual’,’GarageQual’, ‘GarageCond’, ]:<br> train[feat] = train[feat].map(mp) <br>mp = {‘N’:0, ‘Y’:2 , ‘P’:1}<br>for feat in [‘CentralAir’, ‘PavedDrive’]:<br> train[feat] = train[feat].map(mp)<br>mp = {‘Typ’:8, ‘Min1’:7, ‘Min2’:6, ‘Mod’:5, ‘Maj1’:4, ‘Maj2’:3, ‘Sev’:2, ‘Sal’:1}<br>train[‘Functional’] = train[‘Functional’].map(mp)<br>mp = {‘Gtl’:1 ,’Mod’:2 , ‘Sev’:3}<br>train[‘LandSlope’] = train[‘LandSlope’].map(mp)</pre><p>Now what new features can we add??? We have FullBath and HalfBath. Halfbath, though do not influence the SalePrice much. But what if we create a feature called TotalBathrooms? It will help. So add features like this.</p><pre>train[‘TotBath’] = train[‘BsmtFullBath’]+train[‘FullBath’]+.5*(train.BsmtHalfBath+train.HalfBath)<br>train[‘Overall_Score’] = train.OverallQual*train.OverallCond<br>train[‘Total_area’] = train[‘1stFlrSF’]+train[‘2ndFlrSF’]+train.TotalBsmtSF<br>train[‘Garage_Score’] = train.GarageQual*train.GarageCond<br>train[‘Kitchen_Score’] = train.KitchenAbvGr*train.KitchenQual<br>train[‘Bsmt_Score’] = train.BsmtQual*train.BsmtCond</pre><p>We also have the other categorical features (nominal features) that should be converted to numerical. For example there is the Feature called Street, which includes two categories, Grvl and Pave, referring to Gravel and Paved street types. So how to convert this to numbers. Assigning 1 and 0 to them will mean that the category with 1 will be more important than the category with 0. But actually both of them are just different categories and there is nothing like, one superior to other. So the solution for this is One Hot Encoding. This can be easily done than explained. So what were going to do is create two new features called Street_Pave and Street_Grvl and assign 1 and 0 in the columns depending on what type of street the house have. So assign 1 in Street_Grvl and 0 in Street_Pave if the house has Gravel Street. And assign 1 in Street_Pave and 0 in Street_Grvl if the house has Paved Street. Doing this in python using pandas is as simple as calling the get_dummies function from pandas on the train dataset.</p><pre>train = pd.get_dummies(train)</pre><p>So our data is almost ready for modelling. Just one last step. The values in different features are at different scales. For example, the <em>GrLiVArea </em>will have values in range of thousands and MasVnrArea will have values in range of hundreds. So we need to normalize the features before applying Machine Learning techniques. I am using StandardScalar function from scikit learn for this. What it does is, it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.</p><p>And i need to remove the outlier that i came across above. Actually outliers should have been removed much earilier. But as there are only two ouliers, it is not going to matter. I can do it now.</p><pre>train = train.loc[~(train.GrLivArea &gt;4000)]</pre><p>And I am going to divide the training data to train_x and train_y, to apply it to the ML model.</p><pre>train_x = train.drop(‘SalePrice’, axis = 1)<br>train_y = pd.DataFrame(train.SalePrice)<br>index = train_x.columns<br>from sklearn.preprocessing import StandardScaler<br>scaler = StandardScaler()<br>train_x = scaler.fit_transform(train_x)<br>train_x = pd.DataFrame(train_x, columns = index)</pre><p>And our train data is ready now. I am going to do the same for the test dataset.</p><pre>test.drop([&#39;PoolQC&#39;, &#39;MiscFeature&#39;, &#39;Alley&#39;, &#39;Fence&#39;, &#39;FireplaceQu&#39;, &#39;LotFrontage&#39;, &#39;GarageType&#39;, &#39;GarageYrBlt&#39;, &#39;GarageFinish&#39;,&#39;BsmtExposure&#39;, &#39;BsmtFinType2&#39;, &#39;BsmtFinType1&#39;,&#39;MasVnrArea&#39;, &#39;MasVnrType&#39;], axis = True, inplace = True)<br>test.drop(test[test.Electrical.isna()].index, axis = 0, inplace = True)<br>NA = [ &#39;GarageQual&#39;, &#39;GarageCond&#39;, &#39;BsmtCond&#39;, &#39;BsmtQual&#39;]<br>for na in NA:<br>    test[na].fillna(&#39;NA&#39;, inplace = True)<br>    NA = [&#39;GarageQual&#39;, &#39;GarageCond&#39;,&#39;BsmtCond&#39;, &#39;BsmtQual&#39;]<br>for na in NA:<br>    test[na].fillna(&#39;NA&#39;, inplace = True)<br>fill_zero = [&#39;GarageCars&#39;, &#39;GarageArea&#39;]<br>for zeros in fill_zero:<br>    test[zeros].fillna(0, inplace = True)<br>test[&#39;Electrical&#39;].fillna(&#39;SBrkr&#39;, inplace = True)<br>test.MSZoning.fillna(&#39;RL&#39;, inplace = True)<br>test.Utilities.fillna(&#39;AllPub&#39;, inplace = True)<br>test.BsmtFinSF1.fillna(0.0, inplace = True)<br>test.BsmtFinSF2.fillna(0.0, inplace = True)<br>test.BsmtUnfSF.fillna(0.0, inplace = True)<br>test.TotalBsmtSF.fillna(0.0, inplace = True)<br>test.BsmtFullBath.fillna(0.0, inplace = True)<br>test.BsmtHalfBath.fillna(0.0, inplace = True)<br>test.Functional.fillna(&#39;Typ&#39;, inplace = True)<br>test.Exterior1st.fillna(&#39;VinylSd&#39;, inplace = True)<br>test.Exterior2nd.fillna(&#39;VinylSd&#39;, inplace = True)<br>test.KitchenQual.fillna(&#39;TA&#39;, inplace = True)<br>test.SaleType.fillna(&#39;WD&#39;, inplace = True)<br>test.drop(&#39;Id&#39;, axis = 1, inplace = True)<br>features = [&#39;OverallQual&#39;, &#39;GrLivArea&#39;]<br>for feat in features:<br>    test[feat+&#39;_p2&#39;] = test[feat] **2<br>    test[feat+&#39;_p3&#39;] = test[feat] **3<br>test.drop([&#39;TotRmsAbvGrd&#39;, &#39;GarageArea&#39;], axis =1, inplace = True)<br>mp = {&#39;Ex&#39;: 5, &#39;Gd&#39;:4, &#39;TA&#39;:3, &#39;Fa&#39;:2, &#39;Po&#39;:1, &#39;NA&#39;:0}<br>for feat in [&#39;ExterQual&#39;, &#39;ExterCond&#39;, &#39;BsmtQual&#39;, &#39;BsmtCond&#39;, &#39;HeatingQC&#39;, &#39;KitchenQual&#39;, &#39;GarageQual&#39;, &#39;GarageCond&#39;]:<br>    test[feat] = test[feat].map(mp) <br>mp = {&#39;N&#39;:0, &#39;Y&#39;:2 , &#39;P&#39;:1}<br>for feat in [&#39;CentralAir&#39;, &#39;PavedDrive&#39;]:<br>    test[feat] = test[feat].map(mp)<br>mp = {&#39;Typ&#39;:8, &#39;Min1&#39;:7, &#39;Min2&#39;:6, &#39;Mod&#39;:5, &#39;Maj1&#39;:4, &#39;Maj2&#39;:3, &#39;Sev&#39;:2, &#39;Sal&#39;:1}<br>test[&#39;Functional&#39;] = test[&#39;Functional&#39;].map(mp)<br>mp = {&#39;Gtl&#39;:1 ,&#39;Mod&#39;:2 , &#39;Sev&#39;:3}<br>test[&#39;LandSlope&#39;] = test[&#39;LandSlope&#39;].map(mp)<br>test[&#39;Bathrooms&#39;] = test[&#39;BsmtFullBath&#39;] + test[&#39;FullBath&#39;] + 0.5*(test.BsmtHalfBath + test.HalfBath)<br>test[&#39;Overall_Score&#39;] = test.OverallQual*test.OverallCond<br>test[&#39;Total_area&#39;] = test[&#39;1stFlrSF&#39;]+test[&#39;2ndFlrSF&#39;]+test.TotalBsmtSF<br>test[&#39;Garage_Score&#39;] = test.GarageQual*test.GarageCond<br>test[&#39;Kitchen_Score&#39;] = test.KitchenAbvGr*test.KitchenQual<br>test[&#39;Bsmt_Score&#39;] = test.BsmtQual*test.BsmtCond<br>test = pd.get_dummies(test)<br>testcol = test.columns.tolist()<br>traincol = train_x.columns.tolist()<br>diff = set(traincol).difference(testcol)<br>diff = list(diff)<br>last_cols = train_x[diff]<br>train_x.drop(diff, axis =1, inplace = True)</pre><h3>Model Creation and Evaluation</h3><p>As the target <em>SalePrice </em>is a continues value we can use regression here. As i said earlier, i am not going to focus much on modelling, so i will be just using linear regression. But it is always good to try on multple techniques to get the best possible result.</p><p>I used Ridge model from Scikit learn, which is a Regularised linear regression technique. I saw significant difference in the prediction accuracy, when using normal Linear Regression, and Regularised Linear Regression. Normal Linear Regression is prone to overfitting, while in Ridge, we could control variance with the parameter alpha which imposes a penalty on the weights applied for each feature, thus preventing overfitting.</p><pre>from sklearn.linear_model import Ridge<br>from sklearn.metrics import mean_squared_error as mse<br>model1 = Ridge(alpha = 1)<br>model1.fit(trainx, trainy)<br>print(“THe accuracy of training set si is “, model1.score(train_x, train_y))<br>predictions = model1.predict(test)</pre><p>Using Regularised Linear Regreesion in this dataset gave me the score of 0.12821, which is not the best of what you can get. There are lot of ways in which you can improve accuracy by playing more with the data. We can add more features and still there are lots of features that are left unused. I am still learning to figure out the best ways to improve things. And i will try to update things as i find more.</p><p>Here is the link to my source code on GitHub -</p><p><a href="https://github.com/KamskiJohn/Ames-Housing-Price-Prediction-">https://github.com/KamskiJohn/Ames-Housing-Price-Prediction-</a></p><p>I will be delighted to receive suggestions and let me know whether you found this useful.</p><p>Happy learning…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af595a749d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>