Practical Exam: House sales
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
clean_data = pd.read_csv('house_sales.csv')
clean_data.dropna(subset = ['house_id', 'sale_price'], inplace=True)
clean_data['city'] = clean_data['city'].str.replace('--', 'Unknown').astype('category')
'''
clean_data['sale_date'] = pd.to_datetime(clean_data['sale_date'])
clean_data['months_listed'] = clean_data['months_listed'].fillna(clean_data['months_listed'].mean()).round(1)
clean_data['house_type'] = clean_data['house_type'].replace({
'Det.': 'Detached',
'Semi': 'Semi-detached',
'Terr.': 'Terraced'
}).astype('category')
clean_data['area'] = clean_data['area'].str.replace(' sq.m.','').astype('float').round(1)
'''
missing_city=df['city'].isna().sum()
print(missing_city)Task 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. |
# Use this cell to write your code for Task 2
import pandas as pd
clean_data = pd.read_csv('house_sales.csv')
clean_data.dropna(subset = ['house_id', 'sale_price'], inplace=True)
clean_data['city'] = clean_data['city'].str.replace('--', 'Unknown').astype('category')
clean_data['sale_date'] = pd.to_datetime(clean_data['sale_date'])
clean_data['months_listed'] = clean_data['months_listed'].fillna(clean_data['months_listed'].mean()).round(1)
clean_data['house_type'] = clean_data['house_type'].replace({
'Det.': 'Detached',
'Semi': 'Semi-detached',
'Terr.': 'Terraced'
}).astype('category')
clean_data['area'] = clean_data['area'].str.replace(' sq.m.','').astype('float').round(1)
print(clean_data.info())
print(clean_data.isna().sum().sort_values())Task 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.
# Use this cell to write your code for Task 3
import pandas as pd
df = pd.read_csv('house_sales.csv')
price_by_rooms = df.groupby('bedrooms')['sale_price'].agg(avg_price='mean', var_price='var').reset_index()
price_by_rooms = price_by_rooms.round(1)
print(price_by_rooms)Task 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.
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error as MSE
train_data = pd.read_csv('train.csv')
val_data = pd.read_csv('validation.csv')
train_data = pd.get_dummies(train_data, columns=['city', 'house_type'])
val_data = pd.get_dummies(val_data, columns=['city', 'house_type'])
train_data['sale_date'] = pd.to_datetime(train_data['sale_date'])
val_data['sale_date'] = pd.to_datetime(val_data['sale_date'])
# Extract useful date-related features in train_data
train_data['sale_year'] = train_data['sale_date'].dt.year
train_data['sale_month'] = train_data['sale_date'].dt.month
train_data['sale_day'] = train_data['sale_date'].dt.day
# Repeat the same process for val_data
val_data['sale_year'] = val_data['sale_date'].dt.year
val_data['sale_month'] = val_data['sale_date'].dt.month
val_data['sale_day'] = val_data['sale_date'].dt.day
# Drop the original 'sale_date' columns
train_data.drop('sale_date', axis=1, inplace=True)
val_data.drop('sale_date', axis=1, inplace=True)
# Fit a linear regression model
model = LinearRegression()
model.fit(train_data.drop('sale_price', axis=1), train_data['sale_price'])
# Predict using the model
y_pred = model.predict(val_data)
# Create the base_result dataframe with house_id and predicted price
base_result = pd.DataFrame({'house_id': val_data['house_id'], 'price': y_pred})
# Display the resulting dataframe
print(base_result)
Task 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.
# Use this cell to write your code for Task 5
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
train_data = pd.read_csv('train.csv')
val_data = pd.read_csv('validation.csv')
train_data = pd.get_dummies(train_data, columns=['city', 'house_type'])
val_data = pd.get_dummies(val_data, columns=['city', 'house_type'])
train_data['sale_date'] = pd.to_datetime(train_data['sale_date'])
val_data['sale_date'] = pd.to_datetime(val_data['sale_date'])
# Extract useful date-related features in train_data
train_data['sale_year'] = train_data['sale_date'].dt.year
train_data['sale_month'] = train_data['sale_date'].dt.month
train_data['sale_day'] = train_data['sale_date'].dt.day
# Repeat the same process for val_data
val_data['sale_year'] = val_data['sale_date'].dt.year
val_data['sale_month'] = val_data['sale_date'].dt.month
val_data['sale_day'] = val_data['sale_date'].dt.day
# Drop the original 'sale_date' columns
train_data.drop('sale_date', axis=1, inplace=True)
val_data.drop('sale_date', axis=1, inplace=True)
rf = RandomForestRegressor()
rf.fit(train_data.drop('sale_price', axis=1), train_data['sale_price'])
rf_pred = rf.predict(val_data)
# Create the base_result dataframe with house_id and predicted price
compare_result = pd.DataFrame({'house_id': val_data['house_id'], 'price': rf_pred})
# Display the resulting dataframe
print(compare_result)