0% found this document useful (0 votes)
95 views13 pages

House Price Prediction with ML in Python

This document discusses using machine learning to predict house prices based on various features. It introduces the dataset used, which contains information on over 2900 houses like size, number of bedrooms, age, etc. The text then covers data preprocessing steps like one-hot encoding categorical variables, splitting the data into training and test sets, and fitting three regression models - SVM, random forest and linear regression. It reports the mean absolute percentage error for each model on the test set, finding that the SVM model achieved the lowest error of 0.18, indicating it best predicted house prices from the given features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views13 pages

House Price Prediction with ML in Python

This document discusses using machine learning to predict house prices based on various features. It introduces the dataset used, which contains information on over 2900 houses like size, number of bedrooms, age, etc. The text then covers data preprocessing steps like one-hot encoding categorical variables, splitting the data into training and test sets, and fitting three regression models - SVM, random forest and linear regression. It reports the mean absolute percentage error for each model on the test set, finding that the SVM model achieved the lowest error of 0.18, indicating it best predicted house prices from the given features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Introduction to House Price Prediction
  • Importing Libraries and Dataset
  • Data Preprocessing
  • Exploratory Data Analysis (EDA)
  • Data Cleaning
  • One-Hot Encoding for Categorical Features
  • Model and Accuracy
  • Splitting Dataset into Training and Testing
  • Conclusion

House Price Prediction using Machine

Learning in Python
We all have experienced a time when we have to look up for a new house to buy. But
then the journey begins with a lot of frauds, negotiating deals, researching the local areas
and so on.

House Price Prediction using Machine Learning


So to deal with this kind of issues Today we will be preparing a MACHINE LEARNING
Based model, trained on the House Price Prediction Dataset. 
You can download the dataset from this link.
The dataset contains 13 features :
1 Id To count the records.

2 MSSubClass  Identifies the type of dwelling involved in the sale.

3 MSZoning Identifies the general zoning classification of the sale.

4 LotArea  Lot size in square feet.

5 LotConfig Configuration of the lot

6 BldgType Type of dwelling

7 OverallCond Rates the overall condition of the house

8 YearBuilt Original construction year

Remodel date (same as construction date if no remodeling or


9 YearRemodAdd additions).

1
0 Exterior1st Exterior covering on house

1
1 BsmtFinSF2 Type 2 finished square feet.
1
2 TotalBsmtSF Total square feet of basement area

1
3 SalePrice To be predicted

Importing Libraries and Dataset


Here we are using 
 Pandas – To load the Dataframe
 Matplotlib – To visualize the data features i.e. barplot
 Seaborn – To see the correlation between features using heatmap
 Python3

import pandas as pd

import [Link] as plt

import seaborn as sns

dataset = pd.read_excel("[Link]")

# Printing first 5 records of the dataset

print([Link](5))

Output:
 

As we have imported the data. So shape method will show us the dimension of the
dataset. 

 Python3

[Link]

Output: 
(2919,13)

Data Preprocessing
Now, we categorize the features depending on their datatype (int, float, object) and then
calculate the number of them. 

 Python3

obj = ([Link] == 'object')

object_cols = list(obj[obj].index)

print("Categorical variables:",len(object_cols))
int_ = ([Link] == 'int')

num_cols = list(int_[int_].index)

print("Integer variables:",len(num_cols))

fl = ([Link] == 'float')

fl_cols = list(fl[fl].index)

print("Float variables:",len(fl_cols))

Output: 
Categorical variables : 4
Integer variables : 6
Float variables : 3

Exploratory Data Analysis


EDA refers to the deep analysis of data so as to discover different patterns and spot
anomalies. Before making inferences from data it is essential to examine all your
variables.
So here let’s make a heatmap using seaborn library.
 Python3

[Link](figsize=(12, 6))

[Link]([Link](),

            cmap = 'BrBG',

            fmt = '.2f',

            linewidths = 2,
            annot = True)

Output:

To analyze the different categorical features. Let’s draw the barplot.


 Python3

unique_values = []

for col in object_cols:

  unique_values.append(dataset[col].unique().size)

[Link](figsize=(10,6))

[Link]('No. Unique values of Categorical Features')

[Link](rotation=90)

[Link](x=object_cols,y=unique_values)

Output:
 

The plot shows that Exterior1st has around 16 unique categories and other features have
around  6 unique categories. To findout the actual count of each category we can plot the
bargraph of each four features separately.

 Python3

[Link](figsize=(18, 36))

[Link]('Categorical Features: Distribution')

[Link](rotation=90)

index = 1

for col in object_cols:

    y = dataset[col].value_counts()
    [Link](11, 4, index)

    [Link](rotation=90)

    [Link](x=list([Link]), y=y)

    index += 1

Output:

Data Cleaning
Data Cleaning is the way to improvise the data or remove incorrect, corrupted or
irrelevant data.
As in our dataset, there are some columns that are not important and irrelevant for the
model training. So, we can drop that column before training. There are 2 approaches to
dealing with empty/null values
 We can easily delete the column/row (if the feature or record is not much important).
 Filling the empty slots with mean/mode/0/NA/etc. (depending on the dataset
requirement).
As Id Column will not be participating in any prediction. So we can Drop it.

 Python3

[Link](['Id'],

             axis=1,

             inplace=True)
Replacing SalePrice empty values with their mean values to make the data distribution
symmetric.

 Python3

dataset['SalePrice'] = dataset['SalePrice'].fillna(

  dataset['SalePrice'].mean())

Drop records with null values (as the empty records are very less).

 Python3

new_dataset = [Link]()

Checking features which have null values in the new dataframe (if there are still any).

 Python3

new_dataset.isnull().sum()

Output:

 
OneHotEncoder – For Label categorical features
One hot Encoding is the best way to convert categorical data into binary vectors. This
maps the values to integer values. By using OneHotEncoder, we can easily convert object
data into int. So for that, firstly we have to collect all the features which have the object
datatype. To do so, we will make a loop.
 Python3

from [Link] import OneHotEncoder

s = (new_dataset.dtypes == 'object')

object_cols = list(s[s].index)

print("Categorical variables:")

print(object_cols)

print('No. of. categorical features: ',

      len(object_cols))

Output:

Then once we have a list of all the features. We can apply OneHotEncoding to the whole
list.

 Python3

OH_encoder = OneHotEncoder(sparse=False)
OH_cols =
[Link](OH_encoder.fit_transform(new_dataset[object_cols]))

OH_cols.index = new_dataset.index

OH_cols.columns = OH_encoder.get_feature_names()

df_final = new_dataset.drop(object_cols, axis=1)

df_final = [Link]([df_final, OH_cols], axis=1)

Splitting Dataset into Training and Testing


X and Y splitting (i.e. Y is the SalePrice column and the rest of the other columns are X)

 Python3

from [Link] import mean_absolute_error

from sklearn.model_selection import train_test_split

X = df_final.drop(['SalePrice'], axis=1)

Y = df_final['SalePrice']

# Split the training set into

# training and validation set

X_train, X_valid, Y_train, Y_valid = train_test_split(

    X, Y, train_size=0.8, test_size=0.2, random_state=0)

Model and Accuracy


As we have to train the model to determine the continuous values, so we will be using
these regression models.
 SVM-Support Vector Machine
 Random Forest Regressor
 Linear Regressor
And To calculate loss we will be using the mean_absolute_percentage_error module. It
can easily be imported by using sklearn library. The formula for Mean Absolute Error : 

SVM – Support vector Machine


SVM can be used for both regression and classification model. It finds the hyperplane in
the n-dimensional plane. To read more about svm refer this.
 Python3

from sklearn import svm

from [Link] import SVC

from [Link] import mean_absolute_percentage_error

model_SVR = [Link]()

model_SVR.fit(X_train,Y_train)

Y_pred = model_SVR.predict(X_valid)
print(mean_absolute_percentage_error(Y_valid, Y_pred))

Output : 
0.18705129
Random Forest Regression
Random Forest is an ensemble technique that uses multiple of decision trees and can be
used for both regression and classification tasks. To read more about random forests refer
this.
 Python3

from [Link] import RandomForestRegressor

model_RFR = RandomForestRegressor(n_estimators=10)

model_RFR.fit(X_train, Y_train)

Y_pred = model_RFR.predict(X_valid)

mean_absolute_percentage_error(Y_valid, Y_pred)

Output : 
0.1929469
Linear Regression
Linear Regression predicts the final output-dependent value based on the given
independent features. Like, here we have to predict SalePrice depending on features like
MSSubClass, YearBuilt, BldgType, Exterior1st etc. To read more about Linear
Regression refer this.
 Python3
from sklearn.linear_model import LinearRegression

model_LR = LinearRegression()

model_LR.fit(X_train, Y_train)

Y_pred = model_LR.predict(X_valid)

print(mean_absolute_percentage_error(Y_valid, Y_pred))

Output : 
0.187416838

Conclusion 
Clearly, SVM model is giving better accuracy as the mean absolute error is the least
among all the other regressor models i.e. 0.18 approx. To get much better results
ensemble learning techniques like Bagging and Boosting can also be used.

Common questions

Powered by AI

Data preprocessing involved several steps: categorizing features by datatype (int, float, object), identifying and separating categorical, integer, and float variables. Categorical features involved converting object data into integer vectors using OneHotEncoder. Data cleaning included handling missing values by either deleting columns/rows or replacing them with mean/mode values, and dropping irrelevant columns like Id. Records with few null values were dropped to maintain data quality. These preprocessing steps ensured the dataset was clean and suitable for building an accurate prediction model .

Exploratory Data Analysis (EDA) is crucial for understanding and visualizing patterns, spotting anomalies, and forming hypotheses for further analysis. In this project, EDA involved using heatmaps to examine feature correlations and barplots to visualize unique values and distributions of categorical variables. EDA helped identify key features affecting house prices and provided insights into data distributions essential for feature selection and model tuning. By clarifying data structure and variable importance, EDA ensured that the modeling process was based on well-understood data patterns, leading to more effective model selection and parameter tuning .

The OneHotEncoder played a crucial role in transforming categorical data into binary vectors, which are suitable for processing by machine learning algorithms. This encoding converts each category into separate feature vectors, allowing the model to interpret categorical variables as numerical inputs. The main advantage is that it prevents the introduction of ordinal relationships among categories, which could mislead the model. By using OneHotEncoding, the predictive accuracy and interpretability of the model are enhanced, as categorical data is accurately represented and analyzed alongside numerical features .

Feature correlation in the dataset is visualized using heatmaps in exploratory data analysis (EDA). The heatmap illustrates the correlation between different features, highlighting which variables tend to increase or decrease together. This visualization is significant for model development as it aids in selecting features that significantly impact the target variable, SalePrice. It helps in identifying multicollinearity among features which can be reduced to improve model performance by ensuring that the chosen inputs are independent and more predictive of the output .

The study used three regression models: Support Vector Machine (SVM), Random Forest Regressor, and Linear Regression. Each model has unique mechanisms for handling data and making predictions. SVM can identify the optimal hyperplane in n-dimensional spaces, Random Forest uses ensemble learning with multiple decision trees to improve predictions, and Linear Regression predicts dependent values based on linear relationships. In this study, the SVM model performed best, showing the lowest mean absolute percentage error among the models, indicating its higher accuracy in predicting house prices .

The dataset used for predicting house prices includes 13 key features: Id, MSSubClass, MSZoning, LotArea, LotConfig, BldgType, OverallCond, YearBuilt, YearRemodAdd, Exterior1st, BsmtFinSF2, TotalBsmtSF, and SalePrice. MSSubClass identifies dwelling types, MSZoning indicates zoning classifications, LotArea gives the lot size, and BldgType describes the type of dwelling. OverallCond rates the house's condition, while YearBuilt and YearRemodAdd provide construction and remodeling dates, respectively. Exterior1st gives the exterior covering type, and basement features are described by BsmtFinSF2 and TotalBsmtSF. These features contribute to the prediction model by representing physical characteristics, age, and condition of the properties that are relevant for determining sale prices .

Among the regression models used, the Support Vector Machine (SVM) had the least mean absolute percentage error. This low error rate suggests higher prediction accuracy, making it advantageous for price prediction by effectively capturing the complex relationships in the data. SVM's ability to construct hyperplanes in higher-dimensional spaces allows for nuanced decision-making and precise predictions, which are particularly useful in the variability and complexity inherent in housing markets .

Splitting the dataset into training and testing sets is significant as it allows for the evaluation of model performance and prevents overfitting. The training set is used to build and train the model, enabling it to learn patterns and relationships within the data. The testing set, held separate, is used to evaluate the model's predictive accuracy. This approach ensures that the model's performance is not only good on known data but also generalizes well to new, unseen data, which is crucial for reliable and realistic price predictions .

Categorical data can pose challenges in machine learning models due to their non-numeric nature, which models typically cannot interpret directly. In this project, categorical data were identified and converted into binary vectors using OneHotEncoder to make them suitable for machine learning models. OneHotEncoder maps categorical values into integer-space representations, allowing the model to process these inputs effectively. This approach was crucial for incorporating categorical features like MSZoning and BldgType into the prediction model without losing relevant information .

Data cleaning is vital because it removes incorrect, corrupted, or irrelevant information that could impair model accuracy and reliability. For the house price prediction dataset, data cleaning involved handling missing values, removing unnecessary columns like Id, and filling null values with statistical measures such as mean or mode. Clean data ensures that the model is trained on accurate representations, influencing the reliability of predictions. This step prevents potential model errors arising from incomplete or misleading data, thus supporting the development of robust and effective predictive models .

House Price Prediction using Machine 
Learning in Python
We all have experienced a time when we have to look up for a new hou
1
2
TotalBsmtSF
Total square feet of basement area
1
3
SalePrice
To be predicted
Importing Libraries and Dataset
Here we are
 
As we have imported the data. So shape method will show us the dimension of the 
dataset. 

Python3
dataset.shape
Output: 
int_ = (dataset.dtypes == 'int')
num_cols = list(int_[int_].index)
print("Integer variables:",len(num_cols))
fl = (dataset.dt
            annot = True)
Output:
 
To analyze the different categorical features. Let’s draw the barplot.

Python3
unique_v
 
The plot shows that Exterior1st has around 16 unique categories and other features have 
around  6 unique categories. To fi
    plt.subplot(11, 4, index)
    plt.xticks(rotation=90)
    sns.barplot(x=list(y.index), y=y)
    index += 1
Output:
 
Data
Replacing SalePrice empty values with their mean values to make the data distribution 
symmetric.

Python3
dataset['SalePric
OneHotEncoder – For Label categorical features
One hot Encoding is the best way to convert categorical data into binary vecto
OH_cols = 
pd.DataFrame(OH_encoder.fit_transform(new_dataset[object_cols]))
OH_cols.index = new_dataset.index
OH_cols.columns

You might also like