Flask is a lightweight Python web framework that helps data scientists turn models and analysis into interactive web applications. This tutorial covers how to use Flask for deploying machine learning models, building APIs, and creating data visualization dashboards. You'll learn how to set up Flask, handle requests, and integrate data science libraries like Pandas and Matplotlib.
What is a Web Framework and a Micro Web Framework?
A web framework is a set of tools and libraries that helps developers build web applications faster by handling common tasks like routing, database management, and security. For example, Django is a full-featured web framework designed for complex applications.
A micro web-framework, like Flask, is lighter and more flexible. It provides only the essentials, allowing developers to add features as needed. This makes micro-frameworks ideal for smaller projects or when you want more control over your app’s components.
Why Flask for Data Science ?
Flask is a lightweight and flexible micro web framework that provides just enough functionality to get a web app running while allowing full control over its structure. Unlike Django, which follows a strict set of rules, Flask gives developers the freedom to design applications as they see fit. This makes it an excellent choice for data scientists who want to quickly build and deploy models without getting tangled in unnecessary complexity.
To learn about Flask in detail from scratch, refer to our Flask Tutorial.
Key points about why Flask is a great choice for Data Science projects.
- Lightweight and Flexible: Flask keeps things simple. You only add the features you need, making it faster and more efficient than heavy frameworks like Django.
- Easily Deploy Models: Instead of running models in Jupyter notebooks, Flask lets you build a web app where users can input data and get predictions instantly.
- Works with Data Science Libraries: Flask plays well with Pandas, NumPy, Scikit-Learn and TensorFlow, making it easy to integrate your models into a web application.
- Fully Customizable: You decide how to structure your app, giving you complete control over scaling and modifying as needed.
- Build APIs for Your Model: Flask allows you to create APIs so that other applications, like mobile apps or external tools, can use your model’s predictions.
- Jinja2 for Dynamic Data Visualization: Flask uses Jinja2 templating, which allows you to display real-time data insights, charts and model predictions dynamically on web pages. This is especially useful for data-driven dashboards and interactive visualizations.
Core Components of Flask
Flask is built on a few important components that work together to help you build web applications efficiently. Two of the key technologies behind Flask are WSGI, which handles communication between your app and the web server, and Jinja2, the powerful template engine used to create dynamic HTML pages.
WSGI (Web Server Gateway Interface)
WSGI is a specification that defines how web servers communicate with Python web applications. It acts as a bridge between the web server (like Apache or Nginx) and your Flask app, allowing the server to send requests to your app and receive responses. This standard interface ensures Flask apps can run smoothly on various servers.
Jinja2 Template Engine
Jinja2 is Flask’s built-in template engine that lets you write HTML pages with dynamic content. Instead of hardcoding HTML, you can use Jinja2’s simple syntax to insert variables, control logic, and loops into your pages, making it easy to generate personalized and data-driven web content.
For a deeper understanding of core components of Flask, refer:
Setting up Flask
Before starting our project, we first need to install and set up the necessary environment to ensure smooth development and avoid dependency conflicts. These are the steps to start a flask project from scratch:
1. Install Python
Flask requires Python, so first check if it’s installed or not on your system. To check, run this command in your terminal:
python --version
If Python is installed, you'll see the version number e.g., Python 3.20.4 and if not then you'll see an error message. If Python isn’t installed, download it from python.org and install it.
2. Create Your Project Folder
To keep things organized, create a dedicated folder for your project. You can either simply create a folder or run this command in terminal to create it:
mkdir flask_project
cd flask_project
These commands will create a folder name "flask_project" and move inside it.
3. Create and Activate a Virtual Environment
A virtual environment is like a separate workspace for your project. It keeps all the necessary libraries and dependencies in one place, so they don’t interfere with other projects on your system.
python -m venv venv
venv\Scripts\activate
Running these commands will create a virtual environment and activate it so that flask can be installed in it.
4. Install Flask
With the virtual environment activated, install Flask using pip:
pip install flask
This installs Flask and its dependencies, such as Werkzeug and Jinja2. You can also verify the installation success by running this command:
flask --version
5. Create Static and Template Folders
Create two folders inside the "flask_project" folder, named "static" and "templates". Flask organizes frontend files using these two special folders to keep everything structured and easy to manage.
- static folder stores files like CSS, JavaScript and images, basically it contains files that don't change dynamically.
- templates folder stores all the HTML files that define the structure of web pages. Flask uses Jinja2 templating, allowing you to insert dynamic content into these HTML files, such as displaying model predictions, charts or user inputs.
6. Create app.py
Create an "app.py" file, this will be our main Flask application. This file will act as the entry point for our project, handling requests and running the app.
For a deeper understanding of Flask basics, including routing and how to launch a Flask app, check out the article- Flask(creating the first simple application).
Flask Routing and HTTP Methods
There are two fundamental concepts that handle directing and processing requests in Flask. The first is routing, which maps URLs to the code that runs. The second is HTTP methods, which describe the type of action the client wants to perform. Together, they allow your Flask app to respond differently depending on the URL visited and the type of request made.
Routing in Flask
Routing in Flask is the process of defining URL patterns and connecting them to specific Python functions called view functions. When a user visits a URL in the browser, Flask matches that URL to a route and calls the corresponding function to generate a response.
Think of routing like a postal service: the URL is the address, and Flask’s routing system figures out which function (or house) should receive and respond to the “mail” (request).
Python
@app.route('/hello')
def hello():
return "Hello, Flask!"
In the above example, visiting http://localhost:5000/hello will display “Hello, Flask!” because Flask routes that URL to the hello function.
Understanding HTTP Methods
HTTP methods specify what kind of action the client (usually a browser) wants to perform on a URL. The most common methods you’ll use in Flask are:
- GET: Used to request data or a page. For example, loading a webpage.
- POST: Used to send data to the server, like submitting a form.
- PUT: Used to update existing data.
- DELETE: Used to remove data.
By default, Flask routes respond to GET requests unless specified otherwise.
You can restrict a route to specific HTTP methods like this:
Python
@app.route('/submit', methods=['POST'])
def submit():
return "Form submitted!"
Here, the /submit route will only respond to POST requests (such as when submitting a form), ignoring GET requests.
To dive deeper into Flask Routing and Request handling, refer:
Building our First Data Science Web Application
Now that we have a basic understanding of Flask Framework, let's use it in a simple data science project. We will build a simple web application where users can enter data, send it to a machine learning model and get predictions. It’s a quick and easy way to make our model interactive and useful.
Problem Statement
Consider a simple and classic problem of House Price Prediction to work on.
The goal is to build a machine learning model that can estimate the price of a house based on factors like its age, total rooms area, number of households and income levels in the area. This is a common real-world problem used in the real estate industry to help buyers, sellers and investors make informed decisions.
In this project, we will:
- Train a machine learning model using historical housing data.
- Save the trained model so it can be used later for predictions.
- Build a simple web application using Flask that allows users to enter house details.
- Process the input, make predictions and display the estimated house price.
By the end, we will have a fully functional House Price Prediction web app where users can enter property details and get instant price estimates.
Dataset
We will use a simple dataset with a few columns. Below is a snippet of the dataset. Click here to download it.
Final Dataframe"train_data" dataset contains the following features, which will be used to train our house price prediction model:
- house_age: The age of the house, normalized between 0 and 1. Older houses have higher values.
- total_rooms_area: The total area of all rooms in the house, also normalized for consistency.
- households: The number of households living in the house, scaled between 0 and 1.
- income: The median income of residents in the area, an important factor influencing house prices.
- house_value: The actual price of the house (our target variable), which the model aims to predict.
Model Used: Linear Regression
The code uses a Linear Regression model, which is a simple yet powerful algorithm for predicting numerical values. It assumes a linear relationship between input features (X) and the target variable (y). The model learns by finding the best-fit line that minimizes the difference between actual and predicted values.
1. Load the Dataset
- Reads the dataset (final_data.csv) into a Pandas DataFrame.
- The dataset contains features (independent variables) and a target variable (house_value).
2. Separate Features and Target Variable
- X: Contains all columns except house_value (predictor variables).
- y: Contains only house_value (the variable we want to predict).
3. Split Data into Training and Testing Sets
- train_test_split() splits the data into 80% training and 20% testing to evaluate model performance.
4. Train a Linear Regression Model
- Initializes a LinearRegression() model.
- Fits the model using training data (X_train, y_train).
5. Save the Trained Model
- Uses joblib.dump() to save the trained model as a .pkl file (house_price_model.pkl).
- This allows the model to be reused later without retraining.
6. File Paths (Ensure Correct Paths)
- The dataset and model paths (path_for_final_dataset & path_to_save_model) should be updated with valid file paths.
Python
# Training and saving the model
import pandas as pd
import joblib
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Load the prepared dataset
data = pd.read_csv(r"path_for_final_dataset\final_data.csv")
# Separate features and target variable
X = data.drop(columns=['house_value'])
y = data['house_value']
# Split 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)
# Train a Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)
# Save the Trained Model
joblib.dump(model, r"path_to_save_model\house_price_model.pkl")
Creating a Flask Application
Now, let's build our Flask application to make our model interactive and user-friendly. We will create an HTML form to take user input, process it in the backend using our trained model and display the predicted house price on the frontend.
Creating HTML Page
In the templates folder, we will create an HTML file named "index.html". This file will contain the HTML code for a simple form where users can enter details like house age, total rooms area, households and income. When the user submits the form, the data will be sent to the backend, where our trained model will process it and predict the house price. Below is the code for our HTML page:
Python
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>House Price Prediction</title>
<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body style="background: rgb(252, 250, 250);">
<div class="container">
<h1 style="text-align:center">House Price Prediction</h1>
<form action="{{ url_for('predict') }}" method="post">
<label for="house_age">House Age:</label>
<input type="text" name="house_age" placeholder="Enter house age" required>
<br><br>
<label for="total_rooms_area">Total Rooms Area:</label>
<input type="text" name="total_rooms_area" placeholder="Enter total rooms area" required>
<br><br>
<label for="households">Number of Households:</label>
<input type="text" name="households" placeholder="Enter number of households" required>
<br><br>
<label for="income">Income:</label>
<input type="text" name="income" placeholder="Enter income" required>
<br><br>
<button type="submit" class="btn btn-primary">Predict Price</button>
</form>
<br>
<h2>{{ prediction_text }}</h2>
</div>
</body>
</html>
Adding CSS
Create a "static" folder in the project directory. Static Folder in flask contains CSS, javascript and media files for the app. Create a "style.css" file and paste the code given below in it.
CSS
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h2 {
margin-bottom: 20px;
color: #333;
}
input {
width: 90%;
padding: 8px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
background-color: #007bff;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
}
button:hover {
background-color: #0056b3;
}
Using Jinja Templates for Dynamic Content
Jinja templates help us make our HTML page dynamic by allowing Flask to send data to it. In our index.html, we use {{ prediction_text }} to show the predicted house price. This means when a user enters their details, Flask processes the input, runs the model and updates the page with the result. Without Jinja, our page would be static and wouldn’t be able to display the prediction.
Developing the Flask App
Now, let's modify our Python app file (app.py). This is where we will set up the web routes, handle user inputs and connect the frontend with our machine learning model. The complete code is provided below along with a detailed explanation of each part.
Python
from flask import Flask, render_template, request
from sklearn.preprocessing import MinMaxScaler
import joblib
import numpy as np
app = Flask(__name__)
# Load the trained model
model = joblib.load(r"path_to_saved_model\house_price_model.pkl")
# Load the scaler used during training
scaler = joblib.load(r"path_to_saved_model\scaler.pkl")
def prepare_data(features):
"""Normalize the input features using the same scaler used during training."""
features_array = np.array(features, dtype=float).reshape(1, -1)
return scaler.transform(features_array) # Apply the same transformation
@app.route('/')
def home():
return render_template('index.html') # Render the HTML page
@app.route('/predict', methods=['POST'])
def predict():
try:
# Get form inputs
house_age = float(request.form['house_age'])
total_rooms_area = float(request.form['total_rooms_area'])
households = float(request.form['households'])
income = float(request.form['income'])
# Prepare data (normalize using the same scaler from training)
input_features = prepare_data([house_age, total_rooms_area, households, income])
# Predict house price
prediction = model.predict(input_features)[0]
return render_template('index.html', prediction_text=f'Estimated House Price: {int(prediction)}')
except Exception as e:
return render_template('index.html', prediction_text=f'Error: {str(e)}')
if __name__ == '__main__':
app.run(debug=True)
Breakdown of app.py code
Let's understand the code for our flask app by breaking it down.
1. Imports & Setup
- Imports Flask for the web app, joblib to load the model and scaler and NumPy for data handling.
- app = Flask(__name__): Creates the web app.
- Loads a saved model (house_price_model.pkl) and scaler (scaler.pkl) for predictions.
2. prepare_data: It's a user defined function that takes input features (e.g., house age, room area), turns them into a NumPy array and normalizes them using the loaded scaler to match training data.
3. @app.route('/'): Renders index.html, the main page with a form for user inputs.
4. @app.route('/predict', methods=['POST'])
- Runs when the form is submitted:
- Grabs inputs (e.g., house_age, income) as numbers.
- Normalizes them with prepare_data().
- Predicts the price using model.predict().
- Displays the result (or an error) on index.html.
5. app.run(debug=True): Starts the local web server in debug mode.
To learn more about app routing in Flask in detail, refer - Flask Routing
Live Demonstration
The app is now ready. Let’s run the Flask server, enter sample input data in the form and check if the model accurately predicts house prices.
Running the Flask Application
In order to test our model on the live web page, we need to run the Flask app in our IDE terminal. Here are the steps to run the flask application:
- Open the terminal in IDE (View > Terminal or press Ctrl + `).
- In the terminal, run the following command - "python app.py".
- Once the app starts, Flask will provide a local server address in the terminal (usually something like http://127.0.0.1:5000/).
- Open a web browser and visit this URL to access the web interface and test the house price prediction model.
After starting the Flask application, we can access the live web page using the provided URL. Below is a snapshot of our web app's home page.
Live HTML pageTesting Application
We can test our model by entering some sample data to see if it works correctly. Below is the snippet of the inputs and the predicted output.
Testing the application
Similar Reads
Data Science Tutorial
Data Science is a field that combines statistics, machine learning and data visualization to extract meaningful insights from vast amounts of raw data and make informed decisions, helping businesses and industries to optimize their operations and predict future trends.This Data Science tutorial offe
3 min read
Data Science Tutorial with R
Data Science is an interdisciplinary field, using various methods, algorithms, and systems to extract knowledge and insights from structured and unstructured data. Data Science combines concepts from statistics, computer science, and domain knowledge to turn data into actionable insights. R programm
3 min read
Learn Data Science Tutorial With Python
Data Science has become one of the fastest-growing fields in recent years, helping organizations to make informed decisions, solve problems and understand human behavior. As the volume of data grows so does the demand for skilled data scientists. The most common languages used for data science are P
3 min read
SQL for Data Science
Mastering SQL (Structured Query Language) has become a fundamental skill for anyone pursuing a career in data science. As data plays an increasingly central role in business and technology, SQL has emerged as the most essential tool for managing and analyzing large datasets. Data scientists rely on
7 min read
Seaborn Datasets For Data Science
Seaborn, a Python data visualization library, offers a range of built-in datasets that are perfect for practicing and demonstrating various data science concepts. These datasets are designed to be simple, intuitive, and easy to work with, making them ideal for beginners and experienced data scientis
7 min read
Statistics For Data Science
Statistics is like a toolkit we use to understand and make sense of information. It helps us collect, organize, analyze, and interpret data to find patterns, trends, and relationships in the world around us.In this Statistics cheat sheet, you will find simplified complex statistical concepts, with c
15+ min read
Is Data Science Hard to Learn?
In today's era, the data is increasing day by day and the business analyze the data and apply machine learning and deep learning techniques to improve the growth of their business. Data Science involves collecting the data, analyzing the data, transforming the data, and extracting the information an
9 min read
What is a Data Science Platform?
In the steadily advancing scene of data-driven navigation, associations are progressively going to refine apparatuses and advancements to bridle the force of data. One such essential component in data examination is the Data Science Platform. This article means to demystify the idea, investigate its
14 min read
How to Setup Anaconda For Data Science?
To start any data science project itâs important to set up your computer with the right tools. Anaconda is one of the most widely used platforms for data science with Python because it consist of many useful libraries and tools which are pre-installed. Please make sure your laptop or PC has at least
4 min read
Storytelling in Data Science
Data science primarily revolves around extracting meaningful insights from vast datasets, Data-science storytelling takes the world of data analysis and adds the storytelling touch to it. In this article, we will learn How Data Storytelling works in data science, How it helps to visualize data, How
15 min read