Predict Loan Approvals with ML

Clean messy bank data and train three ML models to predict loan approvals.

Introduction

30 Second Summary

Banks receive thousands of loan applications every day. Each one needs a decision: approve or reject.

In this project, you will build a loan approval prediction system using Python and machine learning. You will clean a messy dataset with missing values, train three different classification models, and compare their accuracy to find the best one.

What You'll Build

Picture running a single Python script that ingests raw bank data full of gaps, cleans it all up, trains three competing models, and produces a bar chart proving which algorithm predicts loan outcomes most accurately.

By the end of this project, you'll have:

  • A cleaned dataset where every missing value has been filled using statistical strategies like median and mode, ready for modeling.
  • Three trained classification models (Logistic Regression, Decision Tree, and Random Forest) that predict whether a loan gets approved or rejected from applicant data.
  • A visual comparison chart showing each model's accuracy side by side, with the winner clearly identified.
  • Secret Mission: an optional challenge to push your skills further.

Are there any prerequisites?

This project assumes basic Python knowledge and previous experience with at least one ML project. You do not need to be an expert, but you should be comfortable reading Python code and running scripts in a terminal.

Before We Start

Before we dive in, let's lock in what you're about to build and why it matters.

You're about to take a messy, real-world-style loan dataset and turn it into a system that predicts whether a bank should approve or reject a loan application.

Set Up Your Python Environment

Before you can load any data or train machine learning models, you need the right Python libraries installed on your machine. This project uses four libraries that each handle a different part of the machine learning workflow.

In this step, you will create a dedicated project folder, set up your Python file, and install everything your loan prediction system needs.

In this step, get ready to:
  • Create a loan-prediction folder and a loan_prediction.py file.
  • Install pandas, scikit-learn, matplotlib, and seaborn.
  • Verify all four libraries import correctly.
Create your project folder and Python file
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Visual Studio Code and press Enter to open it.
  • Open the built-in terminal by pressing Cmd+` (macOS) or Ctrl+` (Windows).

Windows users

On Windows, use pip instead of pip3 and python instead of python3 for all commands throughout this project.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir loan-prediction
cd loan-prediction
  • In VS Code, click File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the loan-prediction folder, then click Open.

Seeing a trust dialog?

VS Code may ask "Do you trust the authors of the files in this folder?" when you open a new folder. Click Yes, I trust the authors to continue with full functionality.

  • In the Explorer sidebar on the left, hover over the LOAN-PREDICTION header.
  • Click the New File icon (a page with a plus sign).
  • Type loan_prediction.py and press Enter.

You should see loan_prediction.py appear in the Explorer sidebar. The file opens automatically in the editor as an empty tab.

Don't see the Explorer sidebar?

Press Cmd+Shift+E (macOS) or Ctrl+Shift+E (Windows) to toggle the Explorer panel. If you still don't see it, click View, then Explorer.

Help me open the Explorer sidebar in VS Code.

Install the required libraries

Your project needs four Python libraries. Each one handles a specific job in the machine learning pipeline.

  • Open the terminal in VS Code by pressing Cmd+` (macOS) or Ctrl+` (Windows).
  • Install all four libraries by running:
pip3 install pandas scikit-learn matplotlib seaborn

What does each library do?

  • pandas handles data loading and manipulation. You will use it to read the CSV file and clean the dataset.
  • scikit-learn provides machine learning models, evaluation metrics, and data utilities. Logistic Regression, Decision Tree, and Random Forest all come from this library.
  • matplotlib creates charts and plots. You will use it to visualize model comparisons.
  • seaborn builds statistical visualizations on top of matplotlib. You will use it for the missing values heatmap.

The installation may take a minute. You should see Successfully installed messages in the terminal output for each library.

Seeing a permission error or command not found?

  • If you see pip3: command not found, try using pip instead of pip3.
  • If you see a permission error, add --user to the end of the command to install for your account only.
  • Make sure your terminal is open inside VS Code, not a separate terminal window.

Help me fix my pip install error.

Verify the installation

Before you move on, what do you think will happen when you try to import all four libraries in a single command?

  • Verify everything installed correctly by running:
python3 -c "import pandas; import sklearn; import matplotlib; import seaborn; print('All libraries imported successfully')"

You should see All libraries imported successfully printed in your terminal.

Seeing a ModuleNotFoundError?

  • If you see ModuleNotFoundError, the library did not install properly. Rerun the pip3 install command from the previous substep.
  • On Windows, use python instead of python3. The wrong Python binary may not have the libraries you just installed.
  • If you have multiple Python versions installed, make sure pip3 and python3 point to the same Python installation.

Help me fix my ModuleNotFoundError.

Your environment is ready to go. Next up, you will download a real loan dataset and explore what the data actually looks like.

Load and Explore the Data

Your Python environment is set up and ready to go.

Before you can clean anything or train a model, you need to understand what you are working with. How many rows does the dataset have? Which columns contain gaps? Is the data balanced between approved and rejected loans? Answering these questions first tells you exactly what cleaning work lies ahead.

In this step, get ready to:
  • Download the loan dataset from Kaggle and place it in your project folder.
  • Load the data and print its shape, types, and missing value counts.
  • Create two visualizations showing where data is missing and how loan approvals are distributed.
Download the dataset

The dataset for this project lives on Kaggle, a platform that hosts open datasets for machine learning. It contains loan application data with intentional gaps (missing values) scattered across multiple columns.

  • Open the dataset page in your browser:
https://www.kaggle.com/datasets/bsugiarto9/loan-status-prediction-with-added-nans
  • Sign in to your Kaggle account. If you do not have one, click Register to create a free account.
  • Click the Download button near the top of the page. This downloads a ZIP file to your computer.
  • Extract the ZIP file. Inside you will find a CSV file called loan_data_1.csv.
  • Rename loan_data_1.csv to loan_data.csv.
  • Move loan_data.csv into your loan-prediction folder (the same folder that contains loan_prediction.py).
  • Confirm the file is in the right place by running this in your VS Code terminal:
ls

You should see both loan_data.csv and loan_prediction.py listed in the output.

Don't see loan_data.csv?

Make sure you renamed the file from loan_data_1.csv to loan_data.csv. The code later expects this exact filename.

Check that the file landed inside the loan-prediction folder, not in your Downloads or on the Desktop. You can drag it into the folder using Finder (macOS) or File Explorer (Windows).

Help me find my loan_data.csv file

Add imports and load the data

Now that the CSV is in place, you can write the code that loads it into memory and prints a summary. This first look reveals the dataset's size, column types, and how many missing values each column has.

  • Open loan_prediction.py in VS Code and add the following imports and exploration code:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder

What are all these imports for?

You are importing all the libraries upfront so the file is ready for every step ahead. pandas loads and manipulates the data. matplotlib and seaborn create charts.

The scikit-learn imports bring in the three models you will train later (Logistic Regression, Decision Tree, Random Forest) and the tools to split data, encode text, and measure accuracy.

  • Below the imports, add the code that loads the CSV and prints an exploration summary:
# Load the dataset
df = pd.read_csv("loan_data.csv")

# Explore the data
print("Dataset shape:", df.shape)
print("\nFirst 5 rows:")
print(df.head())
print("\nData types:")
print(df.dtypes)
print("\nMissing values per column:")
print(df.isnull().sum())
print("\nBasic statistics:")
print(df.describe())

What does this code do?

pd.read_csv("loan_data.csv") reads the CSV file into a DataFrame, a table-like structure that pandas uses to hold data.

  • df.shape prints the number of rows and columns.
  • df.head() shows the first 5 rows so you can eyeball the raw data.
  • df.isnull().sum() counts the missing values in every column. This is the most important output right now because it tells you exactly where the gaps are.
  • df.describe() gives basic statistics (mean, min, max) for numerical columns.
  • Save loan_prediction.py.
  • Run the script to see your first look at the data:
python3 loan_prediction.py

You should see the dataset shape printed (something like 614 rows and 13 columns), followed by the first 5 rows, data types, and a list of missing values per column. Several columns will show non-zero missing value counts.

Seeing FileNotFoundError?

This means Python cannot find loan_data.csv. Make sure the CSV file is in the same folder as loan_prediction.py. Also confirm your terminal is pointed at the loan-prediction folder by checking the path shown in your terminal prompt.

Help me fix my FileNotFoundError

Visualize missing values and loan distribution

Numbers are great, but a picture makes the gaps jump out. A heatmap shows exactly where missing values cluster across the dataset, and a bar chart reveals whether the data is balanced between approved and rejected loans.

  • At the bottom of loan_prediction.py, add the missing values heatmap:
# Visualize missing values
plt.figure(figsize=(10, 6))
sns.heatmap(df.isnull(), cbar=True, yticklabels=False, cmap="viridis")
plt.title("Missing Values Heatmap")
plt.tight_layout()
plt.savefig("missing_values.png")
plt.show()

What does this chart show?

sns.heatmap(df.isnull()) converts the entire DataFrame into a grid of True/False values (True where data is missing) and colors them. Bright streaks in specific columns mean those columns have gaps you will need to fill.

plt.savefig("missing_values.png") saves the chart as an image file so you can reference it later. plt.show() opens the chart in a window on your screen.

  • Save loan_prediction.py and run the script again:
python3 loan_prediction.py

After the printed output, a chart window opens showing the missing values heatmap. Close the chart window to let the script finish.

Chart window not appearing?

On some systems, the chart window opens behind your editor. Check your taskbar or dock for a Python window. If charts still do not appear, make sure you are running the script from the terminal (not an interactive notebook).

Help me get my matplotlib chart to display

  • Below the heatmap code, add the loan status distribution bar chart:
# Visualize loan status distribution
plt.figure(figsize=(6, 4))
df["Loan_Status"].value_counts().plot(kind="bar", color=["steelblue", "salmon"])
plt.title("Loan Approval Distribution")
plt.xlabel("Loan Status")
plt.ylabel("Count")
plt.tight_layout()
plt.savefig("loan_distribution.png")
plt.show()

What does this chart show?

df["Loan_Status"].value_counts() counts how many loans were approved (Y) versus rejected (N). The bar chart makes the class balance visible at a glance. If one bar is much taller than the other, the data is imbalanced, which is useful to know before training models.

  • Save loan_prediction.py.

Before you run the script, think about what you expect to see. Will both chart windows open? Will the missing values heatmap look different from the bar chart?

  • Run the script one more time:
python3 loan_prediction.py

You should see the dataset shape and missing value counts printed in the terminal. Then two chart windows open one after the other. The first is the missing values heatmap (close it to continue). The second is the loan status bar chart showing approved vs rejected counts.

Where did the PNG files go?

Both missing_values.png and loan_distribution.png are saved in your loan-prediction folder. You can open them anytime to review the charts without re-running the script.

✔️ Awesome, I've got everything!

Great. Double check that you have saved loan_prediction.py and that both chart windows opened when you ran the script.

ⓧ I'd like to double check the full code

Your loan_prediction.py should contain the following sections in order. Scroll up and confirm each block is present:

  • The import block (9 lines starting with import pandas as pd and ending with from sklearn.preprocessing import LabelEncoder).
  • The load and explore block (pd.read_csv followed by five print statements for shape, head, dtypes, isnull, and describe).
  • The missing values heatmap block (starting with plt.figure(figsize=(10, 6)) and ending with plt.show()).
  • The loan distribution bar chart block (starting with plt.figure(figsize=(6, 4)) and ending with plt.show()).

You now have a clear picture of the data. You can see exactly which columns have gaps and how approvals compare to rejections. Next up, you will fill those gaps and get the data ready for machine learning.

Clean the Data

In the previous step, you loaded the loan dataset and explored its structure. The missing values heatmap and column counts revealed gaps scattered across multiple columns.

Machine learning models cannot learn from incomplete rows, so you need to fill those gaps before training. In this step, you will clean the data and then test whether it is truly ready for a model.

In this step, get ready to:
  • Fill missing values using median and mode strategies.
  • Drop the non-predictive ID column and confirm zero missing values.
  • Test whether the cleaned data is ready for a machine learning model.
Fill missing values in numerical and categorical columns

Numerical and categorical columns need different fill strategies. For numbers, the median is a safe default because it is not skewed by extreme outliers. For categories, the mode (the most common value) preserves the dominant pattern.

  • In loan_prediction.py, scroll to the bottom of the file (below the loan status chart code) and add this code to fill the gaps:
# Clean missing values - numerical columns with median
for col in ["LoanAmount", "Loan_Amount_Term", "Credit_History"]:
    df[col] = df[col].fillna(df[col].median())

# Clean missing values - categorical columns with mode
for col in ["Gender", "Married", "Dependents", "Self_Employed"]:
    df[col] = df[col].fillna(df[col].mode()[0])

What does this code do?

The first loop targets LoanAmount, Loan_Amount_Term, and Credit_History. Each gap is replaced by the column's median, so extreme incomes or loan amounts do not pull the fill value off center.

The second loop targets Gender, Married, Dependents, and Self_Employed. Each gap is replaced by the most frequent value in that column. For text categories, the most common answer is the safest assumption.

  • Save loan_prediction.py.
Drop the ID column and confirm zero missing values

The Loan_ID column is a unique identifier for each row. It carries no useful pattern for predicting loan approvals, so keeping it would only add noise.

  • Below the cleaning code you just added, drop the ID column and print the updated missing value counts by adding this code:
# Drop the ID column
df = df.drop("Loan_ID", axis=1)

print("\nMissing values after cleaning:")
print(df.isnull().sum())

What does this code do?

The df.drop("Loan_ID", axis=1) call removes the Loan_ID column entirely. The axis=1 argument tells pandas to drop a column (not a row).

The two print statements then display the missing value count for every remaining column. If the fills worked, every count should be zero.

  • Save loan_prediction.py.
  • Run the script by entering this command in your terminal:
python3 loan_prediction.py

Close the two chart windows that appear (the missing values heatmap and the loan status chart). After the exploration output, you should see Missing values after cleaning: followed by zeros for every column.

Still seeing non-zero counts?

  • Check that your column names in the fill loops match the dataset exactly. Column names are case-sensitive, so LoanAmount is different from loanamount.
  • Make sure the fill code is placed AFTER the visualization code and BEFORE any new code you add later. Order matters because Python runs top to bottom.
  • Confirm you used .mode()[0] for categorical columns (with the [0] index). The .mode() method returns a Series, so [0] picks the first (most common) value.

Why are my missing value counts still not zero?

Test the cleaned data with a model

The data has zero missing values. That sounds model-ready. Let's put that assumption to the test by feeding the cleaned data directly into a Logistic Regression model.

  • At the bottom of loan_prediction.py, add a quick test that splits the data and tries to train a model:
# Quick test - will crash with ValueError
X = df.drop("Loan_Status", axis=1)
y = df["Loan_Status"]
lr_test = LogisticRegression()
lr_test.fit(X, y)

What does this code do?

The first two lines separate the data into features (X, everything except the loan decision) and the target (y, the Loan_Status column).

Then LogisticRegression() creates a basic classification model, and .fit(X, y) asks it to learn the patterns in the data.

  • Save loan_prediction.py.

Before you run the script, what do you think will happen? The data has zero missing values. Will the model train successfully?

  • Run the script to find out:
python3 loan_prediction.py

Close the two chart windows. After the exploration output and the clean zero-count confirmation, the script crashes with a ValueError about converting a string to a float.

This crash is expected

Even though every gap is filled, columns like Gender and Property_Area still contain text strings like Male and Urban. scikit-learn works with numbers only, so it cannot process those text values.

Cleaning missing values was necessary, but it was not enough to make the data model-ready. The next step fixes this by converting every text column into numbers.

✔️ Awesome, I've got everything!

Great. Double check you have saved loan_prediction.py with all the cleaning code and the quick test at the bottom.

ⓧ I'd like to double check the full code

Your loan_prediction.py file is longer than 30 lines at this point. Scroll through your file and confirm these sections appear in order:

  • Imports at the top (pandas, matplotlib, seaborn, sklearn modules).
  • Load the dataset with pd.read_csv("loan_data.csv").
  • Explore the data (shape, head, dtypes, missing values, describe).
  • Visualize missing values (heatmap) and loan status distribution (bar chart).
  • Clean missing values in numerical columns with median, then categorical columns with mode.
  • Drop Loan_ID and print missing values after cleaning.
  • Quick test at the bottom: split X and y, create lr_test = LogisticRegression(), and call lr_test.fit(X, y).

Your data is clean, but it is not model-ready yet. The crash proved that text columns need to become numbers before any algorithm can learn from them. In the next step, you will encode those text values and train your first working model.

Encode Features and Build Logistic Regression

In the last step, you cleaned every missing value in the dataset and confirmed zero gaps remain. But when you tried to fit a model, the script crashed with a ValueError.

That crash happened because columns like Gender and Property_Area still contain text strings. scikit-learn needs every value to be a number before a model can learn from it. In this step, you will convert those text columns into numbers and train your first classification model.

In this step, get ready to:
  • Encode categorical text columns into numbers using LabelEncoder.
  • Split the data into training and test sets.
  • Train a Logistic Regression model and evaluate its accuracy.
Remove the crashing code and encode categorical columns

The ValueError proved that text values like "Male" or "Urban" cannot be fed into a model. Every column needs to be numerical first.

  • In loan_prediction.py, scroll to the bottom of your file.
  • Find these lines:
# Quick test - will crash with ValueError
X = df.drop("Loan_Status", axis=1)
y = df["Loan_Status"]
lr_test = LogisticRegression()
lr_test.fit(X, y)
  • Delete all five of these lines, including the comment. They were a test that proved text columns crash the model.

Now you need to convert every text column into numbers. LabelEncoder assigns each unique text value an integer. For example, "Male" might become 1 and "Female" becomes 0.

  • Add the following code at the bottom of your file, right after the print(df.isnull().sum()) line:
# Encode categorical features
le = LabelEncoder()
for col in ["Gender", "Married", "Dependents", "Education",
            "Self_Employed", "Property_Area", "Loan_Status"]:
    df[col] = le.fit_transform(df[col])

What does this code do?

  • LabelEncoder() creates an encoder that maps each unique text value in a column to an integer.
  • The for loop runs fit_transform on every categorical column, replacing text like "Yes" and "No" with numbers like 1 and 0.
  • Loan_Status is included because the target column also contains text ("Y" and "N") that needs to become numerical.

Why LabelEncoder instead of one-hot encoding?

LabelEncoder is the simpler approach. It assigns a single number to each category. One-hot encoding creates a new column for every category, which adds complexity.

For tree-based models like Decision Tree and Random Forest, LabelEncoder works well because trees split on thresholds without assuming any ordering between the numbers.

  • Save loan_prediction.py.
  • Run the script to verify the encoding works:
python3 loan_prediction.py

After the exploration output and chart windows, you see "Missing values after cleaning:" with all zeros. The script finishes cleanly this time with no ValueError.

Still seeing a ValueError?

  • Make sure you deleted all five lines of the crashing test code, including the comment.
  • Check that your encoding loop lists all seven columns exactly as shown, including "Loan_Status".
  • Verify that your encoding code is below the df.drop("Loan_ID", axis=1) line, not above it.
  • Help me debug my LabelEncoder ValueError.
Split the data into training and test sets

With all columns now numerical, you can split the data into two groups. The model trains on one group and gets tested on the other, so you can measure how well it predicts on data it has never seen.

  • Add the following code at the bottom of loan_prediction.py:
# Split features and target
X = df.drop("Loan_Status", axis=1)
y = df["Loan_Status"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

print(f"\nTraining set: {X_train.shape[0]} samples")
print(f"Test set: {X_test.shape[0]} samples")

What does this code do?

  • X holds all the feature columns (everything except Loan_Status). y holds only the target column, which is what the model tries to predict.
  • train_test_split randomly divides the data. test_size=0.2 keeps 20% of rows for testing and 80% for training.
  • random_state=42 locks in the random split so you get the same result every time you run the script.
  • Save loan_prediction.py and run the script again:
python3 loan_prediction.py

After the exploration output, you now see two new lines showing the training and test set sizes.

Not seeing the training and test sizes?

  • Make sure the new code is below the encoding block, not inside it.
  • Check that your print lines have the f prefix before the opening quote. Without it, Python prints the curly braces literally.
  • Help me debug my train_test_split output.
Train your first model with Logistic Regression

Your data is clean, encoded, and split. Time to train the first model. Logistic Regression draws a boundary between the two classes and predicts which side of the boundary each loan application falls on.

  • Add the following code at the bottom of loan_prediction.py:
# Model 1: Logistic Regression
lr_model = LogisticRegression(max_iter=1000, random_state=42)
lr_model.fit(X_train, y_train)
lr_pred = lr_model.predict(X_test)
lr_acc = accuracy_score(y_test, lr_pred)

print("\n--- Logistic Regression ---")
print(f"Accuracy: {lr_acc:.4f}")
print(classification_report(y_test, lr_pred))
print("Confusion Matrix:")
print(confusion_matrix(y_test, lr_pred))

What does this code do?

  • LogisticRegression(max_iter=1000, random_state=42) creates the model. max_iter=1000 gives the algorithm enough iterations to find the best boundary. The default of 100 often triggers a convergence warning on this dataset.
  • .fit(X_train, y_train) trains the model on your training data. .predict(X_test) generates predictions for the test set.
  • accuracy_score compares the predictions to the actual answers. classification_report breaks accuracy down into precision, recall, and F1-score for each class.
  • confusion_matrix shows exactly how many predictions were correct vs incorrect.
  • Save loan_prediction.py.

Before you run the script, take a guess. Do you think Logistic Regression will predict loan approvals with more than 75% accuracy?

  • Run the script to find out:
python3 loan_prediction.py

The ValueError is gone. After the exploration output and training set sizes, you see the Logistic Regression accuracy printed as a decimal between 0 and 1.

Below it, a classification report shows precision, recall, and F1-score for each class. A confusion matrix follows with the exact correct and incorrect prediction counts.

Seeing a convergence warning?

  • Double-check that max_iter=1000 is set in your LogisticRegression() call. The default value of 100 is not enough iterations for this dataset.
  • Help me fix my LogisticRegression convergence warning.

✔️ Awesome, I've got everything!

Great. Double check you have saved loan_prediction.py and that the script runs without errors.

ⓧ I'd like to double check the full code

Your loan_prediction.py file is now too long to show in one block. Scroll up through your file and confirm these sections are present, in this order:

  • Imports at the top (pandas, matplotlib, seaborn, sklearn modules, LabelEncoder).
  • Load the dataset and explore it (shape, head, dtypes, missing values, describe).
  • Visualize missing values heatmap and loan status distribution bar chart.
  • Clean missing values (median for numerical, mode for categorical) and drop Loan_ID.
  • Encode categorical features with LabelEncoder (seven columns).
  • Split features (X) and target (y), then train_test_split with test_size=0.2 and random_state=42.
  • Model 1: Logistic Regression with max_iter=1000 printing accuracy, classification report, and confusion matrix.

Make sure the crashing test code (lr_test = LogisticRegression() and lr_test.fit(X, y)) is completely removed.

Your first model is trained and scored. One model is not enough to know if you have chosen the best approach. In the next step, you will build two more models and compare all three to find the winner.

Secret mission

Engineer New Features to Boost Performance

Your models are trained, but are they seeing the full picture? In this bonus challenge, you will engineer new features from existing columns and measure whether they boost your model accuracy.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally, so there are no ongoing costs or cloud resources to worry about. Decide whether to keep your project files, or delete them entirely.

Resources you used:

  • The loan-prediction folder on your Desktop (contains loan_prediction.py, loan_data.csv, and generated chart images).
  • Python packages installed via pip3: pandas, scikit-learn, matplotlib, and seaborn.

Keep everything running

No action needed. Choose this if you want to keep experimenting with your models or try different datasets.

  • Your loan-prediction folder stays on your Desktop with all your scripts and charts.
  • The installed Python packages remain available for future projects.
  • If you created a Kaggle account to download the dataset, that account stays active.

Pause - I'll come back to this later

There are no running processes to stop. Your files and packages sit idle on disk until you need them again.

  • Close the loan_prediction.py tab in VS Code to declutter your workspace.
  • Everything stays on your machine. When you are ready to come back, open the loan-prediction folder in VS Code and pick up where you left off.

Delete - I don't want to use this again

Remove all project files and uninstall the packages you added.

  • Close any open files from the loan-prediction folder in VS Code.
  • Delete the project folder by running this command on macOS/Linux:
rm -rf ~/Desktop/loan-prediction
  • On Windows, run this command instead:
rmdir /s /q %USERPROFILE%\Desktop\loan-prediction
  • Uninstall the Python packages by running:
pip3 uninstall pandas scikit-learn matplotlib seaborn -y

Keep packages for future projects

If you plan to do more data science or ML projects, consider keeping pandas, scikit-learn, matplotlib, and seaborn installed. They are widely used across ML projects and take no disk space worth worrying about.

Nice Work!

Nice Work!

You just built a complete loan approval prediction system from messy, real-world data. You took a dataset full of gaps and text values, cleaned it up, trained three different machine learning models, and proved which one performs best with a visual comparison.

You've learned how to:

  • Clean messy data by filling missing values with median and mode strategies, then encode categorical text into numbers using LabelEncoder so models can process them.
  • Train and evaluate three classification models (Logistic Regression, Decision Tree, and Random Forest) using accuracy scores, classification reports, and confusion matrices.
  • Compare multiple models side by side with a bar chart to identify which algorithm predicts loan approvals most accurately.
  • Secret Mission: Engineered new features (TotalIncome and LoanIncomeRatio) from existing columns and measured their impact on model performance.

Ready to quiz yourself?