Predicting House Sale Prices
RealAgents is a real estate company that focuses on selling houses.
RealAgents sells a variety of types of house in one metropolitan area.
Some houses sell slowly and sometimes require lowering the price in order to find a buyer.
In order to stay competitive, RealAgents would like to optimize the listing prices of the houses it is trying to sell.
They want to do this by predicting the sale price of a house given its characteristics.
If they can predict the sale price in advance, they can decrease the time to sale.
Data
The dataset contains records of previous houses sold in the area.
| Column Name | Criteria |
|---|---|
| house_id | Nominal. Unique identifier for houses. Missing values not possible. |
| city | Nominal. The city in which the house is located. One of 'Silvertown', 'Riverford', 'Teasdale' and 'Poppleton'. Replace missing values with "Unknown". |
| sale_price | Discrete. The sale price of the house in whole dollars. Values can be any positive number greater than or equal to zero. Remove missing entries. |
| sale_date | Discrete. The date of the last sale of the house. Replace missing values with 2023-01-01. |
| months_listed | Continuous. The number of months the house was listed on the market prior to its last sale, rounded to one decimal place. Replace missing values with mean number of months listed, to one decimal place. |
| bedrooms | Discrete. The number of bedrooms in the house. Any positive values greater than or equal to zero. Replace missing values with the mean number of bedrooms, rounded to the nearest integer. |
| house_type | Ordinal. One of "Terraced" (two shared walls), "Semi-detached" (one shared wall), or "Detached" (no shared walls). Replace missing values with the most common house type. |
| area | Continuous. The area of the house in square meters, rounded to one decimal place. Replace missing values with the mean, to one decimal place. |
Task 1
The team at RealAgents knows that the city that a property is located in makes a difference to the sale price.
Unfortuntately they believe that this isn't always recorded in the data.
Calculate the number of missing values of the city.
-
You should use the data in the file "house_sales.csv".
-
Your output should be an object
missing_city, that contains the number of missing values in this column.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.read_csv('house_sales.csv')
df.info()
print(df['city'].value_counts())
# The missing values of the 'city' column are not N/A values but marked as '--'
missing_city = df[df['city'] == '--']['city'].count()
missing_cityTask 2
Before you fit any models, you will need to make sure the data is clean.
The table below shows what the data should look like.
Create a cleaned version of the dataframe.
-
You should start with the data in the file "house_sales.csv".
-
Your output should be a dataframe named
clean_data. -
All column names and values should match the table below.
| Column Name | Criteria |
|---|---|
| house_id | Nominal. Unique identifier for houses. Missing values not possible. |
| city | Nominal. The city in which the house is located. One of 'Silvertown', 'Riverford', 'Teasdale' and 'Poppleton' Replace missing values with "Unknown". |
| sale_price | Discrete. The sale price of the house in whole dollars. Values can be any positive number greater than or equal to zero. Remove missing entries. |
| sale_date | Discrete. The date of the last sale of the house. Replace missing values with 2023-01-01. |
| months_listed | Continuous. The number of months the house was listed on the market prior to its last sale, rounded to one decimal place. Replace missing values with mean number of months listed, to one decimal place. |
| bedrooms | Discrete. The number of bedrooms in the house. Any positive values greater than or equal to zero. Replace missing values with the mean number of bedrooms, rounded to the nearest integer. |
| house_type | Ordinal. One of "Terraced", "Semi-detached", or "Detached". Replace missing values with the most common house type. |
| area | Continuous. The area of the house in square meters, rounded to one decimal place. Replace missing values with the mean, to one decimal place. |
categories = df.columns
for column in categories:
print(df[column].value_counts())
df['city'] = df['city'].replace('--','Unknown')
# No missing or invalid values in 'sale_price' or 'sale_date'
#print(df[df['sale_price'] < 0])
df.isna().sum()
# Replace missing values in 'months_listed' by rounded mean of filled values
mean_months = round(np.mean(df['months_listed'].dropna()),1)
df['months_listed'] = df['months_listed'].fillna(mean_months)
# No missing or invalid values in 'bedrooms'
# Assuming Det., Semi and Terr. values correspond to Detached, Semi-detached and Terraced, respectively, and matching accordingly
df['house_type'] = df['house_type'].replace('Det.','Detached')
df['house_type'] = df['house_type'].replace('Semi','Semi-detached')
df['house_type'] = df['house_type'].replace('Terr.','Terraced')
print(df['house_type'].value_counts())
# No missing or invalid values in 'area' but remove 'sq.m.' and convert to float
df['area'] = df['area'].str.strip('sq.m.')
df['area'] = df['area'].astype('float')
clean_data = df
clean_dataTask 3
The team at RealAgents have told you that they have always believed that the number of bedrooms is the biggest driver of house price.
Producing a table showing the difference in the average sale price by number of bedrooms along with the variance to investigate this question for the team.
-
You should start with the data in the file 'house_sales.csv'.
-
Your output should be a data frame named
price_by_rooms. -
It should include the three columns
bedrooms,avg_price,var_price. -
Your answers should be rounded to 1 decimal place.
sns.boxplot(data=clean_data,x='bedrooms',y='sale_price').set(title='Sale Price vs # of Bedrooms')
price_by_rooms = clean_data.groupby('bedrooms')['sale_price'].agg(['mean','var']).round(1)
price_by_rooms.columns = ['avg_price','var_price']
price_by_rooms = price_by_rooms.reset_index(level='bedrooms')
price_by_roomsTask 4
Fit a baseline model to predict the sale price of a house.
-
Fit your model using the data contained in “train.csv”
-
Use “validation.csv” to predict new values based on your model. You must return a dataframe named
base_result, that includeshouse_idandprice. The price column must be your predicted values.
training = pd.read_csv('train.csv')
training_ids = training['house_id']
training_no_id = training.drop(columns=['house_id','sale_date'])
features = training_no_id.drop(columns=['sale_price'])
X_train = pd.get_dummies(features,columns=['city','house_type'])
# Apply log transformation to prevent predicting negative price values that are illogical
y_train = np.log(training_no_id['sale_price'])
# This problem calls for a simple linear regression model as we can already see a positive correlation between the number of bedrooms and the sale_price, and this model is easy to fit and interpret
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train,y_train)
validation = pd.read_csv('validation.csv')
validation_ids = validation['house_id']
num_bedrooms = validation['bedrooms']
validation_no_id = validation.drop(columns=['house_id','sale_date'])
X_test = pd.get_dummies(validation_no_id,columns=['city','house_type'])
y_pred_lr = np.exp(lr.predict(X_test)).round(1)
# Sanity check to see if predicted values match our expectations for price values (they do) and no negative price values as expected
sns.boxplot(x=num_bedrooms,y=y_pred_lr)
base_result = pd.DataFrame({'house_id':validation_ids,'price':y_pred_lr})
base_resultTask 5
Fit a comparison model to predict the sale price of a house.
-
Fit your model using the data contained in “train.csv”
-
Use “validation.csv” to predict new values based on your model. You must return a dataframe named
compare_result, that includeshouse_idandprice. The price column must be your predicted values.
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()
rf.fit(X_train,y_train)
y_pred_rf = np.exp(rf.predict(X_test)).round(1)
# Sanity check to see if predicted values match our expectations for price values (they do) and no negative price values as expected
sns.boxplot(x=num_bedrooms,y=y_pred_rf)
compare_result = pd.DataFrame({'house_id':validation_ids,'price':y_pred_rf})
compare_result