Saturday, 31 July 2021

House Price Prediction using Flask

 



House Price Prediction using Flask


Introduction:


   In this project, I developed the predictive power of a model trained on houses price data. It deploys with flask API and using Linear Regression to predict the price value. Deploy Machine Learning Model Using Flask to take a model from python code.


    This blog offers you a step-by-step instruction guide with source code, so you can build your model. It is not designed to be a deep dive into model design, statistical analysis, improvement, and validation. If you want to learn more, please check out my blog site: Techy Scientists.


It contains the following parts:


  1. Setup your environment
  2. Build your house price prediction model
  3. Create flask API
 

Setup your environment


   To run the web app on your local computer, install the required libraries, These packages are 


  1.   python 3.8.0
  2.   flask 2.0.1
  3.   werkzeug 2.0.1
  4.   sci-kit learn
  5.   pandas
  6.   numpy
  7.   pickle



Build your house price prediction model


Step 1: Understand the data


  The first step of model prediction is to understand the data. It is more important to all machine learning and deep learning projects. You can find more information about the data, go to House Price - Advanced Regression Techniques competition in Kaggle (Note: If you don't know Kaggle, please check this blog What is Kaggle? How to use it?). And it is also available in my repositories and find the dataset or click this link: dataset.


Step 2: Import the Packages


  Create a python file (for example house.py). After installed the required packages, import packages  in your python file.


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import pickle

Step 3: Import the data

    Next, import the data using pandas
df = pd.read_csv('house_data.csv')
    
Step 4: Feature Selection 

    Remove the unwanted features (Columns), now choose columns are  number of bedrooms, number of bathrooms, number of floors, year of build, and price of the house. In price of the house is the target value. We trained the model in the other four columns to find the price of the house.
columns = ['bedrooms', 
	'bathrooms', 
	'floors', 
	'yr_built', 
	'price']

df = df[columns]

X = df.iloc[:, 0:4]
y = df.iloc[:, 4:]

Step 5: Split the data
    
    We want to create a model, must have split it into training and testing. the model trained by training dataset and then apply the evaluation of model used by test dataset.
X_train, X_test, y_train, y_test = 
train_test_split(X, y, test_size=0.25)

Step 6: Create Machine Learning Model
    
    Now, we use Linear regression model to predict the house price.
lr = LinearRegression()
lr.fit(X_train, y_train)


Step 7: Dump the model using pickle

    It used to store the model data in a file

pickle.dump(lr, open('model.pkl', 'wb'))


Create Flask API


    Flask is a web framework for python. It is used for managing HTTP request and render templates. Now, start to create basic flask API (for example app.py). 

    Pickle load function is used to load the model data in flask API. App route('/') map to home page('index.html') and App route(/predict) map to predict function, it is also call in home page. In predict function get the values from the form and then used them for model prediction.

from flask import Flask, render_template, request
import numpy as np
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/predict', methods=['GET', 'POST'])
def predict():
    val1 = request.form['bedrooms']
    val2 = request.form['bathrooms']
    val3 = request.form['floors']
    val4 = request.form['yr_built']
    arr = np.array([val1, val2, val3, val4])
    arr = arr.astype(np.float64)
    pred = model.predict([arr])

    return render_template('index.html', 
    	data=int(pred))


if __name__ == '__main__':
    app.run(debug=True)

Finally, create simple form in html
<!DOCTYPE html>
<html>

<head>
    
<link rel='stylesheet' type='text/css' 
	media='screen'
	href="{{ url_for('static', 
    	filename='css/main.css') }}">
</head>

<body>

<h1>HOUSE PRICE PREDICTION</h1>
<form action="{{url_for('predict')}}" method="POST">
Bedrooms: <input type="number" name='bedrooms' 
	placeholder="Enter the no of Bedrooms"><br>
Bathrooms: <input type="number" name='bathrooms' 
	placeholder="Enter the no of Bathrooms"><br>
Floors: <input type="number" name='floors' 
	placeholder="Enter the no of Floors"><br>
Year of Build: <input type="number" name='yr_built' 
	placeholder="Enter year of Build"><br>
<input type="submit" value="predict" class="submit">
</form>
<p> House Price is: {{data}}</p>

</body>
</html>


Preview:





Conclusion:


    To run code on your computer, following command in terminal
python app.py
    In summary, we created the House Price Prediction using Linear Regression and deploy with Flask application of the given  dataset. If you want to source code, check this GitHub link: House Price Prediction using Flask.

No comments:

Post a Comment