Machine learning has been used for years to provide image recognition, spam detection, natural speech understanding, product recommendations and medical diagnoses. Today, machine learning algorithms can help us improve cybersecurity, ensure public safety and improve medical outcomes. Machine learning systems can also make customer service better and cars safer.
When I started experimenting with machine learning, I wanted to come up with an application that would solve a real-world problem but wouldn't be too complicated to implement. I also wanted to practice working with regression algorithms. So I started looking for a problem worth solving. Here's what I came up with.
If you're going to sell a house, you need to know what price tag to put on it. And a computer algorithm can give you an accurate estimate!
In this post, I'll show you how I wrote a regression algorithm to predict house prices.
Regression in a nutshell
Simply put, regression is a machine learning tool that helps you make predictions by learning, from existing statistical data, the relationships between your target parameter and a set of other parameters. By this definition, the price of a house depends on parameters such as the number of bedrooms, living area, location and so on. If we apply machine learning to these parameters, we can calculate house values in a given geographic area.
The idea of regression is quite simple: given enough data, you can observe the relationship between your target parameter (the output) and the other parameters (the inputs), and then apply this relationship function to real observed data.
To show how a regression algorithm works, we'll take only one parameter into account to predict the price: a house's living area. It's reasonable to assume there's a linear relationship between area and price. As we remember from high school, a linear relationship is represented by a linear equation:
y = k0 + k1 * x
In our case, y equals the price and x equals the area. Predicting the price of a house is as simple as solving the equation (where k0 and k1 are constant coefficients):
price = k0 + k1 * area
We can calculate these coefficients ( k0 and k1 ) using regression . Let's say we have 1,000 known house prices in a given area. Using a learning technique, we can find a set of coefficient values. Once we've found them, we can plug in different area values to predict the resulting price.

[In this graph, y is the price and x is the living area. The black dots are our observations. The moving lines show what happens when k0 and k1change .
However, there's always a deviation, or difference, between a predicted value and the actual value. If we have 1,000 observations, we can calculate the total deviation across all items by summing the deviations for each k0 and k1 combination .
Regression takes every possible value for k0 and k1 and minimizes the total deviation; that, in short, is the idea of regression.

In real life, though, there are other challenges you have to deal with. House prices obviously depend on more than one parameter, and there's no clear linear relationship among all of these parameters.
Now I'll tell you how I used regression algorithms to predict house prices in the project.
How to use regression algorithms in machine learning
1. Collect the data
The first step in any kind of machine learning analysis is collecting the data, which has to be valid. If you can't guarantee the validity of your data, there's no point in analyzing it. You need to pay attention to the source you get your data from.
For my purposes, I relied on the database of one of the largest real estate portals in Sakarya. Since the real estate market in Sakarya is tightly regulated, I didn't have to check its validity.
At the start, I had to do some data mining, because the data I needed was available in various formats across multiple sources. In most real-world projects, you'll have to do some data mining too. We won't discuss data mining here, though, since it isn't really relevant to the topic.
For the purposes of this article, let's assume that all the real estate data I found is in the format shown below.
2. Analyze the data
Once you've collected the data, it's time to analyze it. After parsing the data, I got the following records:
-
{"has_garden": 1, "years": 1980, "lng": 4.640685, "has_garage": 0, "number_of_changes": "2", "area": 127, "bedrooms_count": "4", "com_time" : 57, "price": 305000, "energy_label": 1, "lat": 52.30177, "rooms_count": "5", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 4.656503, "has_garage": 0, "number_of_changes": "3", "area": 106, "bedrooms_count": "3", "com_time" : 64, "price": 275000, "energy_label": 3, "lat": 52.35456, "rooms_count": "4", "life_quality": 5, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 4.585596, "has_garage": 0, "number_of_changes": "3", "area": 106, "bedrooms_count": "3", "com_time" : 74, "price": 244000, "energy_label": 3, "lat": 52.29309, "rooms_count": "4", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 4.665817, "has_garage": 0, "number_of_changes": "2", "area": 102, " bedrooms_count": "4", "com_time" : 77, "price": 199900, "energy_label": 3, "lat": 52.14919, "rooms_count": "5", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 4.620336, "has_garage": 0, "number_of_changes": "1", "area": 171, "bedrooms_count": "3", "com_time" : 79, "price": 319000, "energy_label": 1, "lat": 52.27822, "rooms_count": "4", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 5.062804, "has_garage": 1, "number_of_changes": "1", "area": 139, "bedrooms_count": "5", "com_time" : 38, "price": 265000, "energy_label": 5, "lat": 52.32992, "rooms_count": "6", "life_quality": 7, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 5.154957, "has_garage": 1, "number_of_changes": "2", "area": 129, "bedrooms_count": "4", "com_time" : 57, "price": 309500, "energy_label": 1, "lat": 52.35634, "rooms_count": "5", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
-
{"has_garden": 1, "years": 1980, "lng": 4.622486, "has_garage": 0, "number_of_changes": "1", "area": 125, "bedrooms_count": "4", "com_time" : 76, "price": 289000, "energy_label": 1, "lat": 52.2818, "rooms_count": "5", "life_quality": 6, "house_type": 1, "is_leasehold": 0}
Here's what the fields mean:
-
has_garden - does the property have a garden? 1 - true, 0 - false
-
years - year of construction
-
lat, lng - the house's location coordinates
-
area- total living area
-
has_garage - does the property have a garage? 1 - true, 0 - false
-
bedrooms_count - number of bedrooms
-
rooms_count - total number of rooms
-
energy_label - energy efficiency label (assigned to every house in Sakarya)
-
life_quality - a quality-of-life score calculated by the local authorities for each district
-
house_type - property type (1 - house, 0 - apartment)
-
com_time - commute time to central Sakarya
-
changes_count - the number of transfers if you travel to central Sakarya by public transport
I worked on the assumption that all of these are measurable data that affect the price of a house. Of course, there may be more parameters that matter, such as the condition and location of the house. But those parameters are more subjective and nearly impossible to measure, so I ignored them.
3. Check the correlation between parameters
Now you need to check for strong correlations between the given parameters. If there are any, remove one of the parameters. In my dataset, there was no strong relationship between the values.
4. Remove outliers from the dataset
Outliers are observation points that lie far from the other observations. For example, according to my data, there was a 50-square-meter house priced like a 500-square-meter one. Houses like that can exist on the market for various reasons, but they aren't statistically significant. I want to make a price prediction based on the market average, so I won't take outliers like these into account.
Most regression methods require outliers to be explicitly removed from the dataset, since they can significantly affect the results. To remove the outliers, I used the following function:
def get_outliners(dataset, outliers_fraction=0.25):
clf = svm.OneClassSVM(nu=0.95 * outliers_fraction + 0.05, kernel="rbf", gamma=0.1)
clf.fit(dataset)
result = clf.predict(dataset)
return result
This will return -1 for outliers and 1 for non-outliers. Then you can do something like this:
training_dataset = full_dataset[get_outliners(full_dataset[analytics_fields_with_price], 0.15)==1]
After that, you'll only have the non-outlier observations. Now it's time to start the regression analysis.
5. Choose a regression algorithm
There's more than one way to do regression analysis. What we're looking for is the best prediction accuracy for our data. But how can we check the accuracy? A common way is to calculate the r ^ 2 score, which is basically a squared difference between the actual and predicted values .
It's important to remember that if we use the same dataset both for learning and for checking our accuracy, our model may overfit. This means it will show excellent accuracy on that particular dataset but fail completely when given new data.
A common approach to solving this problem is to split the original dataset into two parts, then use one for learning and the other for testing. This way, we simulate new data for our learning model, and if there's overfitting, we can detect it.

We can split our dataset using an 80/20 ratio. We'll use 80 percent for training and the remaining 20 percent for testing. Let's take a look at this piece of code:
// code for estimating algorithm quality
from sklearn import svm
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.svm import SVR
from sklearn.metrics import r2_score
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
#prepare dataset
#....
#spilt dataset
Xtrn, Xtest, Ytrn, Ytest = train_test_split(training_dataset[analytics_fields], training_dataset[['price']],
test_size=0.2)
# model = RandomForestRegressor(n_estimators=150, max_features='sqrt', n_jobs=-1)
models = [LinearRegression(),
RandomForestRegressor(n_estimators=100, max_features='sqrt'),
KNeighborsRegressor(n_neighbors=6),
SVR(kernel='linear'),
LogisticRegression()
]
TestModels = pd.DataFrame()
tmp = {}
for model in models:
# get model name
m = str(model)
tmp['Model'] = m[:m.index('(')]
# fit model on training dataset
model.fit(Xtrn, Ytrn['price'])
# predict prices for test dataset and calculate r^2
tmp['R2_Price'] = r2_score(Ytest['price'], model.predict(Xtest))
# write obtained data
TestModels = TestModels.append([tmp])
TestModels.set_index('Model', inplace=True)
fig, axes = plt.subplots(ncols=1, figsize=(10, 4))
TestModels.R2_Price.plot(ax=axes, kind='bar', title='R2_Price')
plt.show()
As a result, I got the following chart:

As you can see, the RandomForest regressor showed the best accuracy, so we decided to use this algorithm in production.
Price prediction in production works the same way as in our test code, except that there's no longer any need to calculate r ^ 2 or switch between models .
At this point, we can offer sound price predictions. We can compare a house's actual price with our predicted price and observe the deviation.
I ranked the houses I analyzed from undervalued to overvalued. This software only ranks houses in Sakarya.
Naturally, my house price prediction algorithm isn't 100 percent accurate. But it's acceptable to me, because my original goal was to create a kind of custom ranking to reduce the amount of manual work for people who are thinking about buying or selling a house and want to compare prices on the market.