Backend Walkthrough
Understanding how the Flask server processes loan applications and makes predictions
Overview
The backend of our Smart Credit Risk System is built using Flask, a lightweight
Python web framework. The main file is app.py, which handles all the server logic,
model loading, and prediction making.
Think of the backend as the "brain" of our system. When a user submits the loan application form, the backend receives the data, processes it, runs it through our trained Machine Learning model, and returns the prediction result.
1. Imports
At the top of app.py, we import the necessary libraries:
from flask import Flask, render_template, request
import joblib
import pandas as pd
What Each Import Does:
-
Flask: This is our web framework. It helps us create a web server that can
receive HTTP requests and send responses.
render_templateis used to display HTML pages, andrequesthelps us get data from the user's form submission. - joblib: This library is used to save and load our trained Machine Learning model. Think of it as a way to "freeze" our trained model so we can use it later without retraining.
- pandas: This is a powerful library for working with data. We use it to organize the user's input into a format that our model can understand (like a table or spreadsheet).
2. Model Loading
After importing libraries, we load our pre-trained model:
# Load the trained model (our 'brain')
model = joblib.load('credit_risk_model.pkl')
💡 How joblib.load Works
joblib.load() retrieves the trained Random Forest model from a file called
credit_risk_model.pkl. This file contains all the "knowledge" our model learned
during training - all the patterns it discovered about which loan applicants are safe vs risky.
Why do we load it once? Loading the model takes time and memory. By loading it once when the server starts, we can reuse it for every prediction request without reloading it each time. This makes our system much faster!
3. Feature Engineering
Before making a prediction, we need to calculate a special feature called interest_burden. This feature helps the model understand how much of a person's income goes toward paying loan interest.
# Calculate interest burden
interest_burden = (loan_amnt * (loan_int_rate / 100)) / person_income
Above: Code editor screenshot showing the interest_burden feature engineering logic.
Breaking Down the Formula:
- loan_amnt: The total amount of money the person wants to borrow
- loan_int_rate: The annual interest rate (as a percentage, e.g., 5%)
- person_income: The person's annual income
Example: If someone wants a $10,000 loan at 5% interest and earns $50,000 per year:
- Interest per year = $10,000 × (5 / 100) = $500
- Interest burden = $500 / $50,000 = 0.01 (or 1% of income)
A lower interest burden means the person can more easily afford the loan payments, which is a good sign!
4. Routes
Routes are like different "pages" or "endpoints" in our web application. Each route handles a specific type of request from the user's browser.
Route 1: Home Page (@app.route('/'))
@app.route('/')
def home():
return render_template('index.html')
This route shows the main form page. When someone visits our website's homepage, Flask displays
the index.html file, which contains the loan application form.
@app.route('/')means "when someone visits the root URL (like www.example.com/)"render_template()finds and displays the HTML file
Route 2: Prediction Endpoint (@app.route('/predict'))
@app.route('/predict', methods=['POST'])
def predict():
# Get data from the form
age = request.form['age']
income = request.form['person_income']
loan_amnt = request.form['loan_amnt']
# ... more fields ...
# Prepare data for the model
features = pd.DataFrame({...})
# Make prediction
prediction = model.predict(features)[0]
probability = model.predict_proba(features)[0]
# Return result
return render_template('index.html',
prediction_text=result)
How the Prediction Route Works:
-
Receives Data: When the user clicks "Submit" on the form, the browser sends
a POST request to
/predictwith all the form data. -
Extracts Information:
request.formgets each field from the form (age, income, loan amount, etc.) - Prepares Data: We organize the data into a pandas DataFrame (like a table) that matches the format the model expects.
-
Makes Prediction:
model.predict()gives us the answer (SAFE or RISKY), andmodel.predict_proba()gives us the confidence percentage. -
Shows Result: We send the result back to the user's browser, which displays
it on the page using
{{ prediction_text }}in the HTML template.
Summary
The backend (app.py) is the engine that powers our Smart Credit Risk System:
- It loads the trained model when the server starts
- It receives loan application data from users
- It processes and prepares the data (including calculating interest_burden)
- It runs the data through the model to get predictions
- It sends the results back to the user's browser
All of this happens in seconds, making it feel instant to the user!