Firstly, you’ll need Python installed on your machine, along with a few key libraries that are essential for machine learning and deployment.
To install these libraries, run the following command in your terminal or command prompt:
bashCopypip install pandas scikit-learn fastapi uvicorn
Once these libraries are installed, you’re all set to begin!
To predict house prices, we need a dataset that contains both the features (like the number of rooms, location, etc.) and the target variable (the house price). A great starting point is the Boston Housing Dataset, which is widely used for this type of problem.
Here’s how you can load and prepare the dataset for training:
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# Load the Boston Housing Dataset
boston = load_boston()
data = pd.DataFrame(boston.data, columns=boston.feature_names)
data['PRICE'] = boston.target
# Split the data into features (X) and target (y)
X = data.drop('PRICE', axis=1)
y = data['PRICE']
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Check the first few rows of the dataset
print(X_train.head())
pythonCopy
In this code:
X
) and target (y
).For predicting house prices, a simple yet effective model to start with is Linear Regression. It predicts a numerical value (house price) based on a linear relationship with the input features.
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Create a Linear Regression model
model = LinearRegression()
# Train the model on the training data
model.fit(X_train, y_train)
# Make predictions on the test data
y_pred = model.predict(X_test)
# Evaluate the model's performance using Mean Squared Error
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
pythonCopy
In this code:
Once the model is trained, you’ll want to save it to a file so it can be used later for making predictions through a web application.
We will use the joblib library to save our trained model:
bashCopypip install joblib
Now, save the model:
pythonCopyimport joblib
# Save the trained model to a file
joblib.dump(model, 'house_price_model.pkl')
This saves the trained model to a file called house_price_model.pkl
, which can be loaded later when deploying the model.
Now, let’s deploy our machine learning model using FastAPI. FastAPI will allow us to expose our model as a web service where users can send data and receive predicted house prices in real-time.
Create a new Python file called main.py
for your FastAPI application. Here’s the code to create an API that accepts house features and returns the predicted price.
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import numpy as np
# Load the trained model
model = joblib.load('house_price_model.pkl')
# Create the FastAPI app
app = FastAPI()
# Define the input format for house features
class HouseFeatures(BaseModel):
CRIM: float
ZN: float
INDUS: float
CHAS: float
NOX: float
RM: float
AGE: float
DIS: float
RAD: float
TAX: float
PTRATIO: float
B: float
LSTAT: float
# Create the prediction endpoint
@app.post('/predict')
def predict_price(features: HouseFeatures):
# Convert the features into a numpy array
input_data = np.array([[features.CRIM, features.ZN, features.INDUS, features.CHAS, features.NOX,
features.RM, features.AGE, features.DIS, features.RAD, features.TAX,
features.PTRATIO, features.B, features.LSTAT]])
# Predict the price
price = model.predict(input_data)
# Return the predicted price
return {"predicted_price": price[0]}
pythonCopy
Now that we’ve written the FastAPI application, we need to run it. FastAPI uses Uvicorn as the server to run the app.
To run your app, use the following command:
bashCopyuvicorn main:app --reload
This starts the FastAPI server, and the API will be available at http://127.0.0.1:8000
. The --reload
flag ensures that the app reloads automatically when you make changes.
To test your API, you can use a tool like Postman or curl. Here’s how to test it using curl:
bashCopycurl -X 'POST' \
'http://127.0.0.1:8000/predict' \
-H 'Content-Type: application/json' \
-d '{
"CRIM": 0.1,
"ZN": 0,
"INDUS": 6.2,
"CHAS": 0,
"NOX": 0.4,
"RM": 6.5,
"AGE": 65.2,
"DIS": 4.5,
"RAD": 2,
"TAX": 290,
"PTRATIO": 15,
"B": 396.9,
"LSTAT": 5.5
}'
The response should look like this:
jsonCopy{
"predicted_price": 22.93982341820699
}
This is the predicted price of the house based on the provided features.
To integrate the API into a website, you can create a simple front-end where users input house features, and the front-end sends a request to your FastAPI backend to get the predicted price.
Here’s an example HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House Price Prediction</title>
</head>
<body>
<h1>Predict House Price</h1>
<form id="houseForm">
<label for="CRIM">Crime Rate: </label><input type="number" id="CRIM" step="0.01"><br>
<label for="ZN">Residential Area: </label><input type="number" id="ZN" step="0.01"><br>
<!-- Add other input fields here -->
<button type="submit">Predict Price</button>
</form>
<h2 id="priceResult"></h2>
<script>
document.getElementById("houseForm").addEventListener("submit", function(event) {
event.preventDefault();
const features = {
CRIM: parseFloat(document.getElementById("CRIM").value),
ZN: parseFloat(document.getElementById("ZN").value),
// Add other features here
};
fetch('http://127.0.0.1:8000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(features)
})
.then(response => response.json())
.then(data => {
document.getElementById("priceResult").innerText = "Predicted Price: " + data.predicted_price;
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
</body>
</html>
This HTML page allows users to input house features, sends them to the FastAPI server, and displays the predicted price.