Machine Learning Model deploy on Website using Flask-Furniture Price Prediction

Emily Chen
Emily Chen

--

Inspired by 12-Hour ML Challenge, I was wondering if I can deploy any machine learning models on website, which provide better interface for users to get access to. Several steps should be considered before starting the development:

  1. Define problem: University students who live in campus or outside of the campus will have the need of buying or selling their furniture during the start and the end of semester. When it comes to selling or buying the furniture, students may encounter a problem of setting the appropriate price to sell; For new coming students, they may want to make sure that the furniture hasn’t being overpriced.
  2. Idea and solution: Gather or scrap data from furniture website(i.e. Ikea, Room to go), then build a machine learning model that could be embedded in a website for students to predict the price of their furniture.
  3. Gather data and sources: An easy way to get data is to search on Kaggle, it has thousands of datasets opened to everyone. The Ikea dataset includes information about the furniture, such as category, sell online, other colors, designer, depth, width, length, price, etc. What I am going to do is to take these variables, including feature(category, length… ) and target(price) variables to build a decision tree model that can used to predict potential furniture price.
  4. Define process and timeline: Before jumping into the practice, we should make a clear design of the process and timeline. Based on personal skill background and project scale, each project may have different timeline. For this project, I decided to build three website pages and one machine learning model embedded into one of the website. Since I am not familiar with JavaScript, it may take longer to add functions in the website, so I scheduled a time of five days:

Day1. build decision tree model → furniture.csv & model.py

Day2. build furniture prediction html template and css style → fill.html & style.css

Day3. embed model into furniture prediction website, deploy model using Flask → model.pkl & app.py

Day4. add functions to the website and add 2 more website(book introduction, room introduction) → book.html & room.html

Day5. deploy website for users using Heroku or GCP → Procfile & requirements.txt

5. Decide which tools to use: For the python IDE, I chose Jupyter Notebook for building ML model, since you can get the result line by line and check which line leads to error. For the Python libraries, I used Scikit learn, Pandas, Numpy , pickle, flask packages. Then I built the flask file on Spyder, which run whole chunk of code altogether. For the HTML and CSS file, I chose Notepad++ to edit, since it provides a friendly user interface. For version control, I go with Sourcetree that could commit and push the file on github remote repository. For website deployment, I chose Heroku, which is a cloud Paas that support different languages to build, run and scale application.

Machine Learning model deployment architecture

let’s start with building ML model. First take a look at the dataset:

furniture.csv (feature: category, sellable_online, other_colors, depth, height, width; target: price)

In the machine learning field, there are two major categories: supervised and unsupervised learning. In supervised learning, the training set you feed to the algorithm includes the target solutions, called labels. One task is classification, which learn to do binary classification; Another task is to predict a target numeric value, such as the price of a furniture in this project. This task is called regression. In this project, we are going to use Decision Tree regression algorithm to build the model. On the other hand, in unsupervised learning, the training data is unlabeled, the system tried to learn without instruction, algorithms such as K-means, PCA, One-class SVM, Apriori.

Before building the model, we have to clean up the data, first include columns that we need then replace missing values with the mode value in that column. For categorical variable, we should convert it to numerical variable to fit into the model, I chose LabelEncoder in this project, we could also choose OneHotEncoder based on different needs.(Label Encoder vs. One Hot Encoder in Machine Learning)

After cleaning up the data, we should separate feature and target columns, then split the data into train and test set, and take the feature and target data in the train set to build a decision tree regression model, and now we build a model successfully! We could also test the model performance using MSE, RMSE.

The last step is to convert our model into a pickle file that is used for building the flask app. When we run the last two lines of code, it will generate a model.pkl file into your working directory. Pickling is a way to convert a python object into a character stream. This character stream contains all the information necessary to reconstruct the object in another python script.

model snapshot in Spyder(copied from Jupyter Notebook)

After building the model, we then start to build our app using Flask, Flask is a micro web framework written in Python, it allows you to build a web app by providing libraries,tools and technologies. We first install numpy, pickle and necessary functions from flask, load the pickle file and initialize the flask app.

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

@app.route(…) is called a decorator. A decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Therefore, each function is going to be triggered when you go to a specific page of the site. So when we go to the home page, the function will be triggered to show the furniture html template.

@app.route('/predict',methods=['POST'])
def predict():
features = request.form.to_dict()
features = list(features.values())
features = list(map(int, features))
final_features = np.array(features).reshape(1,6)
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('fill.html',
prediction_text='家具價格為(Furniture prediction price is): $ {}'.format(output))

When we press the predict button on the website, we will enter the /predict page. The POST will read the input value (category, sellable_online, other_colors, depth, width, length) from request.form.to_dict(), this function will turn the value to dictionary, then we change the value to list and map those values to integer. The final feature should be reshaped as a 1x6 array to be fit into the model and predict the furniture price. The predict function should have the same name in the html file, so when we press the predict button, it will trigger the predict function to show the fill.html template and show the price in the place where we set in the html file.

For example, in the html file, we should add the code below before writing the input parameter form.

<form action="{{url_for('predict')}}"method="post">
<tr>
<th>深度(Depth):</th>
<td><input type="text" name="depth" placeholder="Depth cm" required="required" />
</tr> ...
</form>

When we want to click to another web page, we can write:

@app.route('/room', methods=['GET', 'POST'])
def room():
if request.method == 'POST':
return redirect(url_for('fill'))
return render_template('room.html')

Similarly, you should also add the url_for() code in the main page html:

<li><a href="{{ url_for('room')}}">房間介紹</a></li>
app.py snapshot in Spyder

Next, let’s take a look at the html file. Start from the header, I put the css and favicon link in the header, remember that the css, image or JavaScript file should be placed under the static file, when all those files being wrapped under the static file, html template will grab the source we need in the static file, and the html url link should be written like this: <link rel=”stylesheet” href=”{{ url_for(‘static’, filename=’css/style2.css’) }}”>

file structure for the flask app

In the body section, I have a section that is used to link to different website pages, and under that section, I put a table that contains 6 input section for users to enter the feature value, after filling out the table, users can press the predict button to get the predict price or press the clear button to clean out all the value they answered in the table.

Also, I added a JavaScript function in the category drop down feature, once users click on the furniture category, the background will be changed to the corresponding image. For example:

background image change demo

I put the price prediction result at the bottom of the body, so when users press the “predict” button, the result will be shown under the page:

furniture price prediction demo

Also, as I mentioned before, I added two more web pages that users can link to from the furniture web page. These two pages are room and books introduction, which may not be necessary for this project, but would add more fun and give us a chance to learn more web developing knowledge!

room.html website demo
book.html website demo

You may wonder how to run the app locally, we can enter app.py in the Anaconda prompt after we change the directory to the app file location. This will trigger if __name__ == “__main__”: app.run(debug=True) to start the server and default port(5000). After we enter app.py in Anaconda prompt, just enter http://127.0.0.1:5000/ on your browser, then you can see your website! Sometimes error may happen when we click on a function, we can take a look at what line of code causes the problem that mentioned on the website to debug the code.

Alright! This is the end of the project, but learning doesn’t end, feel free to check the code for this project on my Github:

https://github.com/yenjungchen80108/furniture-prediction-app

Thanks for reading and hope you have a good day!

email: emily80108@gmail.com

LinkedIn: emilychen80108

References:

  1. 12-Hour ML Challenge
  2. Deploy Machine Learning Model using Flask
  3. Deploy your Machine Learning Model using Flask — Made Easy Now
  4. Turning Machine Learning Models into APIs in Python

--

--