House Price Prediction Using Regression
House Price Prediction Using Regression
ABSTRACT
The objective of the project is the predict the house price by using regression
models. The dataset consist of 23 features and 21613 records. Among the 23
features, there are 18 integer type, 4 float type and 1 objective type. There are no
missing values in the dataset.
Regression models used are linear regression, KNN, SVR, decision tree, random
forest, Gradient boost. The different matrices like ‘R squared’, ‘Mean absolute
error’ and ‘Mean squared error’ are used to evaluate the different models.
Benchmark laid in compare with the final model is linear regression. But, mainly
considering the R squared value the final model could get almost 10% better
results compared to the benchmark model hence concluded to be the final model
Among all the models, Gradient boosting has performed well with trainset
accuracy of 81.9 and testset with 75.5.
lOMoAR c PSD| 59306481
CHAPTER I
1. INTRODUCTION
1.1 Problem statement
A house value is simply more than location and square footage. Like the features
that make up a person, an educated party would want to know all aspects that give
a house its value. For example, you want to sell a house and you don’t know the
price which you can take — it can’t be too low or too high. To find house price
you usually try to find similar properties in your neighborhood and based on
gathered data you will try to assess your house price.
1.2 Objective:
To predict the price of house which is not too high or too low using regression
models. The project challenges to predict the final price of each home.
18
Latitude 0 float64 5034
19
longitude 0 float64 752
20
Living_measure15 0 int64 777
21
Lot_measure15 0 int64 8689
22
Furnished 0 int64 2
23
Total_area 0 int64 11163
Hardware Requirements
Minimum:
• Processor: Intel i3 / AMD Ryzen 3 or equivalent
• RAM: 4 GB (basic model training & prediction)
• Storage: 250 GB HDD / SSD
• GPU: Not required, but useful for small-scale ML tasks (e.g., NVIDIA GeForce
MX series)
• OS: Windows 10 / Linux (Ubuntu 20.04+) / macOS
Recommended:
• Processor: Intel i5 / i7 or AMD Ryzen 5 / 7
• RAM: 8–16 GB (smooth ML model training, Pandas/Numpy handling large
datasets)
• Storage: 512 GB SSD (for datasets & faster processing)
• GPU: NVIDIA GPU with CUDA support (e.g., GTX 1650 / RTX 2060+) if deep
learning involved
• OS: Windows 10/11 (64-bit), Ubuntu 20.04+, or macOS Monterey+
Software Requirements
Operating System:
• Windows / Linux / macOS
Programming Language:
• Python 3.8+
IDE / Development Tools:
• Jupyter Notebook / JupyterLab
• PyCharm / VS Code / Spyder
lOMoAR c PSD| 59306481
CHAPTER II
2.1 Dropping attributes: There are attributes like cid, zip code, longitude
and latitude which are irrelevant in predicting the target variables. Hence after
dropping these attributes the dataset is
lOMoAR c PSD| 59306481
Graphs show the form of the distribution of the data and are a very useful tool
in exploring a dataset. Besides graphs, statistics that summarize the distribution
of the data, are used to transform data into information. The five-number
summary, which forms the basis for a boxplot, is a good example of
summarizing data. The below table is summary statistics of the dataset
lOMoAR c PSD| 59306481
price: Our taget column value is in 75k - 7700k range. As Mean > Median, it
's Right-Skewed.
yr_renovated: House renovation year only 2015. So this column can be used
as Categorical Variable for knowing whether house is renovated or not.
lOMoAR c PSD| 59306481
Lat: Latitude ranges from 47.1559 - 47.7776 As Mean < Median, it's Left-Sk
ewed.
Long: Longitude ranges from -122.5190 to -121.315 As Mean > Median, it's
Right-Skewed.
Living_measure15: Value ranges from 399 to 6,210. As Mean > Median, it'
s Right-Skewed.
Lot_measure15: Value ranges from 651 to 8,71,200. As Mean highly > Med
ian, it's Highly Right-Skewed.
Furnished: Representing whether house is furnished or not. It's a Categorica
l Variable
Total_area: Total area of house ranges from 1,423 to 16,52,659. As Mean is
almost double of Median, it's Highly Right-Skewed
i) Univariate analysis
ii) Bivariate analysis
Groupby the ‘month year’ and ‘price’ and find the mean of price
So the time line of the sale data of the properties is from May-2014 to May-2015
and April month have the highest mean price
lOMoAR c PSD| 59306481
[Link]: Room_bed
Number of bed rooms by using python function value_counts
[Link] : Room_bath
Summary statistics of Price
Living measure is the square footage of the house. Living measure varied from
290 [Link] to 13540 [Link]. There is no much deviation of mode from mean. Almost
lOMoAR c PSD| 59306481
normal distribution with slightly right skewed. Skew factor is 1.47. From the
above graph it is observed that majority of the house's living measure is 2000 [Link]
Many outliers are observed. It needs to be taken care in the future analysis.
lOMoAR c PSD| 59306481
Lot measure varies from 520 to 16.5 Lakh square feet. Distribution is highly
skewed with outliers
Coast is found binary type of data. House which have waterfront view represents
1 and house without waterfront view represents 0. Only 163 houses has waterfront
view.
[Link] Sight (represents how many times sight has been viewed)
Value counts for sight is
Range of the sight varies from 0 to 4. Most of the house have not been viewed.
And the respective values of how many times its been viewed is as shown
Found there are no direct or linear relation between ceil and ceil_measure
2 distribution can be seen. That means there are some properties without
basement and some are with basement.
Boxplot for property which has basement only. We can see that there are many
outliers that needs to addressed.
variation of yr_built can be observed from 1900 to 2014, With more properties
built in the year 2014
2. room_bed: our target variable (price) and room_bed plot is not linear. Its
distribution have lot of gaussians
3. room_bath: It's plot with price has somewhat linear relationship. Distribution
has number of gaussians.
4. living_measure: Plot against price has strong linear relationship. It also have
linear relationship with room_bath variable. So might remove one of these 2.
Distribution is Right-Skewed.
6. ceil: No clear relationship with price. We can see, it's have 6 unique values only.
Therefore, we can convert this column into categorical column for values.
7. coast: No clear relationship with price. Clearly it's categorical variable with 2
unique values.
8. sight: No clear relationship with price. This has 5 unique values. Can be
converted to Categorical variable.
9. condition: No clear relationship with price. This has 5 unique values. Can be
converted to Categorical variable
10. quality: Somewhat linear relationship with price. Has discrete values from 1 -
13. Can be converted to Categorical variable.
11. ceil_measure: Strong linear relationship with price. Also with room_bath and
living_measure features. Distribution is Right-Skewed.
14. yr_renovated: No clear relationship with price. Have 2 unique values. Can be
converted to Categorical Variable which tells whether house is renovated or not.
15. zipcode, lat, long: No clear relationship with price or any other feature.
16. living_measure15: Somewhat linear relationship with target feature. It's same
as living_measure. Therefore we can drop this variable.
18. furnished: No clear relationship with price or any other feature. 2 unique values
so can be converted to Categorical Variable
19. total_area: No clear relationship with price. But it has Very Strong linear
relationship with lot_measure. So one of it can be dropped.
7. furnished: quality
lOMoAR c PSD| 59306481
With increasing in room bed 'Price' is increasing. After 8 room_bed the graph is
following decreasing trend
There is a clear linear relationship can be observed with respect to price and
living_measure. Also few outliers can be visible
lot_measure - data value range is very large so breaking it get better view.
No clear trend is observed between price and lot_measure. Also the correlation
between price and lot_measure is 0.082456. We could drop this feature
ceil - median price increases initially and then falls. There is some slight upward
trend in price with the ceil
lOMoAR c PSD| 59306481
coast - mean and median of waterfront view is high however such houses are very
small in compare to non-waterfront view. Also, living_measure mean and median
is greater for waterfront house. The house properties with water_front tend to
have higher price compared to that of non-water_front properties.
sight - have outliers. The house sighted more have high price (mean and median)
and have large living area as well. Properties with higher price have more no of
sights compared to that of houses with lower price.
condition - as the condition rating increases its price and living measure mean and
median also increases. The price of the house increases with condition rating of the
house
quality - with grade increase price and living_measure increase (mean and
median). There is clear increase in price of the house with higher rating on quality
ceil_measure - price increases with increase in ceil measure. There is upward trend
in price with ceil_measure.
We will create the categorical variable for basement 'has_basement' for houses
with basement and no basement. This categorical variable will be used for further
analysis
lOMoAR c PSD| 59306481
The houses with basement has better price compared to that of houses without
basement.
So most houses are renovated after 1980's. We will create new categorical
variable 'has_renovated' to categorize the property as renovated and non-
renovated. For further analysis we will use this categorical variable.
Trend is not clear with respect to age of the house and Price. Correlation between
them is also very low.
furnished v/s Price
Mean and median of price with respect to furnished
furnished - Furnished has higher price value and has greater living_measure.
Furnished houses have higher price than that of the Non-furnished houses
lOMoAR c PSD| 59306481
CHAPTER III
3. Data Pre-processing
Data preprocessing is the process of transforming raw data into an
understandable format. It is also an important step in data mining as we cannot
work with raw data. The quality of the data should be checked before applying
machine learning or data mining algorithms.
3.1 Outliers handling
We have seen outliers in many of the attributes like columns room_bath,
living_measure, lot_measure, ceil_measure and Basement
Lower bound and upper bound values ranges from -34 to 3740
2. hdf_log_trans: The columns where outliers are found that particular columnis
log transformed
All the three dataframe have been considered for model building seperately
lOMoAR c PSD| 59306481
All the outliers values in both upper and lower limit have been removed
Only 'ceil_measure_log' is considered and the original column have been dropped
Plot a distribution plot for living measure and living measure log
lOMoAR c PSD| 59306481
We got 2128 records which are outliers. Drop these records from dataset
Log transformation
Final dataset
lOMoAR c PSD| 59306481
CHAPTER IV
4. Data modelling
Machine learning model is the product of training a machine learning algorithm
with training data.
While algorithms are simply general approaches to solve an objective, ML
models can evaluate future unknown data and make predictions.
One can create many models from same algorithm, as long as different training
data are available.
Types of ML algorithms
1. Supervised learning:
2. Unsupervised learning:
8. R squared
9. Mean squared error
[Link] absolute error
Model performance for with outliers and log transformation for training data is
more and it is 0.706 and 0.708
Model performance for with outliers and log transformation for test data is more
and it is 0.664 and 0.667
lOMoAR c PSD| 59306481
Support vector machine regressor is fitting worse than horizontal line for all the
dataframes. Hence SVM model is not suitable for the present data.
• Decision tree regressor worked consistently with all dataframes without any
overfitting or underfitting.
• Decision tree gave better result for overall data and bad result for scaled data.
• Random forest regressor gave better and consistant result without overfitting
or underfitting.
• Model performance is better for overall data without dropping out outliers.
• Out of all the algorithms, Linear regression for overall original data gave a
better performance hence that can be considered to be a better and final model.
Improving Performance of all these models will be done by fine tuning the models
by using cross validation, random searchCV and hyperparameters.
Gradient Boost Regressor algorithm is giving a consistent and better result compared to all other
models. Hence, here after Gradient Boost Regressor with log transformation data will be
considered for further analysis
1. The ensemble models (Random Forrest and Gradient Boost Regressor) have
performed well compared to that of linear, KNN, SVR models.
2. The best performance is given by Gradient boosting model with training score-
82%, Testing score 76%
3. The top key features that drive the price of the property
are:'living_measure_log','furnished_1','house_age','living_measure15','coast_1','
yr_built' etc...
lOMoAR c PSD| 59306481
After removing few variables which are not relevant in predicting the target, the
final independent variables are
Since it is learnt that the best model is Gradient Boost for our regression problem. Also, the
hyperparameter tuning is done by [Link] best model with best hyperparameter and the
lOMoAR c PSD| 59306481
best data is found from our analysis. And the same is considered for model building without one
hot encoding.
Model evaluation
Many models were built for different data sets before concluding the best model
for the given problem as explained in the previous section in detail.
At the end of numerous trials carried out on the different data sets and the models,
the gradient boosting regressor is selected as the final model for the current
project.
The objective of the model in the present study was to predict the house price
given many features or attributes about the house as accurately as possible so that
the difference between actual and predicted price is minimized. Hence the
problem was regression problem predicting a real valued number as an output.
To achieve the above objective various models were tried and at last the gradient
boosting algorithm with 200 numbers of estimators and 0.1 as a learning rate gave
the best result out of the lot and hence concluded to be the final model for the
present case.
The output of the model confirmed that the features like ‘living measure’,
‘furnished’ and ‘house age’ were most prominent features in predicting the house
price along with many other parameters.
To decide the best model among the lot, the models were compared with the
benchmark model ‘Linear regression’ performance using ‘R squared’, ‘Mean
absolute error’ and ‘Mean squared error’ as a evaluation matrices.
Comparison to benchmark
In the present study, instead of keeping the particular value as a benchmark, the
basic linear regression model performance was considered to be a benchmark and
lOMoAR c PSD| 59306481
further different models were built and trained in order improve the results
compared the results of the benchmark model. The benchmark ‘Linear
regression’ model could get us around 65% accurate result in predicting the house
prices.
The different matrices like ‘R squared’, ‘Mean absolute error’ and ‘Mean squared
error’ are used to evaluate the different models. But, mainly considering the R
squared value the final model could get almost 10% better results compared to
the benchmark model hence concluded to be the final model.
The different models performed differently on all the datasets but finally the
ensembles model with proper hyper parameter tuning could give better results in
predicting the house price hence could improve the results compared to
benchmark model results. The better performance could be due to
accommodating the non-linear behaviour in the model which was not present in
the benchmark model and also the generalisation of results of many models due
to the use of ensemble technique in the form of gradient boosting has helped
reduce the bias and variance without losing maximum feature importance and
information from the data. Hence the final model could perform better compared
to the benchmark set.
Visualizations
In addition to quantifying the model and the solution, the below are the relevant
visualizations that support the ideas/insights that gleaned from the data.
Feature importances:
lOMoAR c PSD| 59306481
Heatmap
Bivariate analysis
lOMoAR c PSD| 59306481
Implications
We have arrived at our final model which is able to predict the price of a house with 95% of
confidence interval. Our final model train accuracy is 82% and test accuracy is 76%.
From the above observation it can be seen that a random cross checking is made showing the
comparison of our model's predicting price v/s actual price of the house. Our model’s prediction
can be found in line with the actual price of the house tested for different records.
Limitations
The main limitations of our solution are,
• Treating outliers: there can be found quite numerous outliers in many attributes.
Removing outliers yielded drop in the model accuracy in almost all the algorithms we
tried.
• Handling categorical variable: for the same, we tried one hot encoding which results
in the increase of number of attributes. That would be very difficult to input the different
attributes when it is taken to production environment.
• Visualization: Since, the number of independent attributes is high the visualization and
drawing the relation between each attribute were not easy.
lOMoAR c PSD| 59306481
We have found outliers individually for each attribute and taken care for the same.
For the final model we have tested by removing dummy variables and the model
behaved smoothly without change in its performance and accuracy. For
visualization we tried univariate, bivariate and multivariate plots and tried to
extract maximum relation among independent variable and between independent
and target variable.
lOMoAR c PSD| 59306481
CHAPTER V
5. CODING
import pandas as pd
import numpy as np
import [Link] as plt
from [Link] import scatter_matrix
import seaborn as sns
from scipy import stats
from sklearn import preprocessing
from [Link] import OneHotEncoder
cal_housing = pd.read_csv('[Link]')
# 1 Explore Data
print(cal_housing.info())
print(cal_housing.head())
print(cal_housing.describe())
print(cal_housing["ocean_proximity"].value_counts())
# 2 Scaling
min_max_test = [Link]()
X_train_minmax_test = min_max_test.fit_transform(cal_housing_numbers)
cal_housing_minmax_scaled_df = [Link](X_train_minmax_test,
columns=number_columns)
print(cal_housing_minmax_scaled_df.head())
standar_test = [Link]()
X_train_standar_test = standar_test.fit_transform(cal_housing_numbers)
cal_housing_standard_scaled_df = [Link](X_train_standar_test,
columns=number_columns)
print(cal_housing_standard_scaled_df.head())
maxabs_test = [Link]()
X_train_maxabs_test = maxabs_test.fit_transform(cal_housing_numbers)
cal_housing_maxabs_scaled_df = [Link](X_train_maxabs_test,
columns=number_columns)
print(cal_housing_maxabs_scaled_df.head())
robust_test = [Link]()
X_train_robust_test = robust_test.fit_transform(cal_housing_numbers)
cal_housing_robust_scaled_df = [Link](X_train_robust_test,
columns=number_columns)
print(cal_housing_robust_scaled_df.head())
lOMoAR c PSD| 59306481
normal_test = [Link]()
X_train_normal_test = normal_test.fit_transform(cal_housing_numbers)
cal_housing_minmax_scaled_df = [Link](X_train_normal_test,
columns=number_columns)
print(cal_housing_minmax_scaled_df.head())
unique_ocean_proximity = cal_housing['ocean_proximity'].unique()
print(unique_ocean_proximity)
ohv_categories = cal_housing[["ocean_proximity"]]
encoder = OneHotEncoder()
housing_cat_ohv = encoder.fit_transform(ohv_categories)
array = housing_cat_ohv.toarray()
encoderDF = [Link](array, columns=encoder.categories_)
dataset = [Link]([cal_housing, encoderDF], axis=1)
dataset = [Link](['ocean_proximity'], axis=1)
print(dataset)
# 4 median value
print(cal_housing.info())
print("Κενές τιμές πριν: ")
print(cal_housing['total_bedrooms'].isna().sum())
median_value = cal_housing['total_bedrooms'].median()
cal_housing['total_bedrooms'].fillna(median_value, inplace=True)
print("Κενές τιμές μετά: ")
print(cal_housing['total_bedrooms'].isna().sum())
# visualize
cal_housing.hist(bins=50, figsize=(15,8.1))
[Link]()
# visual 2
[Link](cal_housing["median_income"],
cal_housing["median_house_value"], alpha=0.1)
[Link]("Median Income")
[Link]("Median House Value")
[Link]("Median Income per Median House Value")
[Link]([0, 16, 0, 550000])
[Link]()
[Link](cal_housing["total_rooms"], cal_housing["median_house_value"],
alpha=0.1)
[Link]("Total Rooms")
[Link]("Median House Value")
[Link]("Total Rooms per Median House Value")
[Link]()
# Perceptron
if __name__ == "__main__":
cal_housing = pd.read_csv('[Link]')
X = cal_housing.iloc[:, :-2].values
y = cal_housing.iloc[:, -2].values
k = 5
fold_size = len(X) // k
accuracies = []
mses = []
maes = []
p = Perceptron(learning_rate=0.01, n_iters=1000)
[Link](X_train, y_train)
predictions = [Link](X_test)
[Link](acc)
[Link](mse)
[Link](mae)
mean_accuracy = [Link](accuracies)
mean_mse = [Link](mses)
mean_mae = [Link](maes)
# least squares
start = k * M
end = (k + 1) * M if k < K - 1 else N
test_indices.append(indices[start:end])
train_indices.append(np.setdiff1d(indices, test_indices[-1]))
return train_indices, test_indices
X_train_mean = [Link](X_train)
Y_train_mean = [Link](Y_train)
Y_pred = m * X_test + c
mse_scores.append(mse)
mae_scores.append(mae)
if __name__ == "__main__":
X = cal_housing.iloc[:, 0]
Y = cal_housing.iloc[:, 1]
[Link](X, Y)
[Link]("X")
[Link]("Y")
[Link]("Linear Regression Fit")
[Link]()
lOMoAR c PSD| 59306481
# MultiLayer NN
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import Sequential
from [Link] import Dense
from [Link] import Adam
from [Link] import EarlyStopping
import [Link] as plt
from [Link] import r2_score
X = [Link][:,0:9]
Y = [Link][:,9]
# Create model
model = Sequential([
Dense(128, activation="relu", input_dim=X_train.shape[1]),
Dense(32, activation="relu"),
Dense(8, activation="relu"),
Dense(1, activation="linear")
])
# Compile model
[Link](loss='mean_squared_error', optimizer=Adam(learning_rate=1e-3,
decay=1e-3 / 200))
# Calculate predictions
PredTestSet = [Link](X_train)
PredValSet = [Link](X_val)
lOMoAR c PSD| 59306481
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, n_iters=1000):
[Link] = learning_rate
self.n_iters = n_iters
self.activation_func = self._unit_step_func
[Link] = None
[Link] = None
[Link] = [Link](n_features)
[Link] = 0
for _ in range(self.n_iters):
SCREENSHOT
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
lOMoAR c PSD| 59306481
CHAPTER VI
6. Conclusions
We have built different models on the datasets with all possible
hyperparameter tuning. Ensembles models particularly Gradient Boost
Regressor is performing better with good accuracy and performance score.
The final best model is pickled for further use and exposed as rest API using
‘flask’ framework which is able to predict the price of the property in the
local machine.
REFERENCE