DEV Community

Mate Technologies
Mate Technologies

Posted on

Build an AI Loan Approval Prediction System with Python πŸ§ πŸ’°

In this step-by-step Dev.to tutorial, we’ll build LoanGuardian v2.1, an AI-powered loan approval prediction system using Python.

This guide is beginner-friendly β€” each section is broken into small code blocks with clear explanations, so you can follow along even if you’re new to machine learning or desktop apps.

πŸ” What We’re Building

By the end of this tutorial, you’ll have:

A desktop GUI app built with Tkinter

An ML model (RandomForest) that predicts loan approval

Automatic handling of large CSV files

Feature detection for categorical & numeric data

A clean exportable prediction workflow

πŸ“¦ GitHub repo: https://github.com/rogers-cyber/python-tiny-tools/tree/main/Loan-approval-prediction-system

πŸ› οΈ Requirements

Install the required libraries:

pip install pandas numpy scikit-learn ttkbootstrap tkinterdnd2
πŸ“ Project Structure
LoanGuardian/
β”œβ”€β”€ main.py
└── requirements.txt

Everything will live inside main.py for simplicity.

🧠 Step 1: Import Required Libraries

We start by importing Python standard libraries, GUI tools, and machine learning packages.

import os, sys, threading
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
Enter fullscreen mode Exit fullscreen mode

These handle:

File selection

UI dialogs

Background processing (to keep the app responsive)

Now the data and ML libraries:

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
Enter fullscreen mode Exit fullscreen mode

🎨 Step 2: Improve the UI with ttkbootstrap

ttkbootstrap gives us modern themes with minimal effort.

import ttkbootstrap as tb
from ttkbootstrap.constants import *
Enter fullscreen mode Exit fullscreen mode

Optional drag-and-drop support:

try:
    from tkinterdnd2 import TkinterDnD, DND_FILES
    DND_ENABLED = True
except ImportError:
    DND_ENABLED = False
Enter fullscreen mode Exit fullscreen mode

🧩 Step 3: Create the Machine Learning Worker

We separate ML logic from the UI using a worker class.

class LoanWorker:
    def __init__(self, files, callbacks, chunk_size=500):
        self.files = files
        self.callbacks = callbacks
        self.chunk_size = chunk_size
Enter fullscreen mode Exit fullscreen mode

Why?

Keeps UI clean

Allows background processing

Scales to large datasets

πŸ“Š Step 4: Train a Sample Loan Model

For demo purposes, we train on a small dataset.

data = pd.DataFrame({
    "Gender": ["Male","Female","Female","Male"],
    "ApplicantIncome": [5000,3000,4000,6000],
    "LoanAmount": [200,100,150,250],
    "Loan_Approved": ["Yes","No","Yes","Yes"]
})
Enter fullscreen mode Exit fullscreen mode

Split features and labels:

X = data.drop("Loan_Approved", axis=1)
y = data["Loan_Approved"]
Enter fullscreen mode Exit fullscreen mode

πŸ”€ Step 5: Encode Categorical Features

Machine learning models require numbers β€” not text.

le = LabelEncoder()
X["Gender"] = le.fit_transform(X["Gender"])
Enter fullscreen mode Exit fullscreen mode

We store encoders so we can reuse them when new CSV files are loaded.

πŸ“ Step 6: Normalize Numeric Data

Normalization keeps values within a predictable range.

scaler = MinMaxScaler()
X[["ApplicantIncome", "LoanAmount"]] = scaler.fit_transform(
    X[["ApplicantIncome", "LoanAmount"]]
)
Enter fullscreen mode Exit fullscreen mode

🌲 Step 7: Train the RandomForest Model

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X, y)
Enter fullscreen mode Exit fullscreen mode

Why RandomForest?

Beginner-friendly

Handles mixed data types

Strong baseline accuracy

πŸ“‚ Step 8: Process Large CSV Files in Chunks

Instead of loading everything at once:

for chunk in pd.read_csv(path, chunksize=500):
    processed = self._preprocess_chunk(chunk)
Enter fullscreen mode Exit fullscreen mode

This makes the app memory-efficient and fast.

πŸ–₯️ Step 9: Build the GUI

Create the main window:

self.root = tb.Window(themename="darkly")
self.root.title("LoanGuardian v2.1")
Enter fullscreen mode Exit fullscreen mode

Add buttons and file input:

tb.Button(text="Start Prediction", command=self.start)
tb.Button(text="Export Results", command=self.export_results)
Enter fullscreen mode Exit fullscreen mode

πŸ“ˆ Step 10: Show Progress Feedback

We animate progress to improve UX.

self.progress = tb.Progressbar(maximum=100)
self.progress["value"] = percent
Enter fullscreen mode Exit fullscreen mode

πŸ’Ύ Step 11: Export Prediction Results

with open(path, "w") as f:
    for file, status in results:
        f.write(f"{file} | {status}\n")
Enter fullscreen mode Exit fullscreen mode

This allows easy reporting or auditing.

πŸš€ Final Result

You now have:

βœ… A production-style ML workflow βœ… Desktop GUI βœ… CSV batch processing βœ… AI-powered predictions

πŸ”— Full Source Code

Clone the project:

git clone https://github.com/rogers-cyber/python-tiny-tools.git

Navigate to:

Loan-approval-prediction-system/
πŸ™Œ What’s Next?

Replace dummy data with real datasets

Save trained models with joblib

Add probability scores

Convert to .exe using PyInstaller

Happy coding! πŸš€

Top comments (0)