# 💳 Credit Card Fraud Detection using Machine Learning
An end-to-end machine learning project that detects potentially fraudulent credit card transactions using **Random Forest, SMOTE, and Streamlit**.
## 📌 Project Overview
Credit card fraud detection is a highly imbalanced classification problem where fraudulent transactions represent only a very small percentage of all transactions.
This project builds a machine learning pipeline that:
* Loads and explores transaction data
* Handles severe class imbalance using **SMOTE**
* Scales numerical features
* Trains a **Random Forest Classifier**
* Evaluates the model using fraud-focused metrics
* Provides an interactive **Streamlit web application**
* Supports both demonstration transactions and CSV-based predictions
**Note:** This project is intended for educational and portfolio purposes. It is not a production banking fraud detection system.
---
## 🎯 Problem Statement
The objective is to classify credit card transactions into two categories:
* 0 → Legitimate transaction
* 1 → Fraudulent transaction
The major challenge is class imbalance. In the dataset, legitimate transactions greatly outnumber fraudulent transactions.
Therefore, accuracy alone is not a reliable measure of model performance.
---
## 📊 Dataset
The project uses the **Credit Card Fraud Detection dataset from Kaggle**.
The dataset contains:
* **284,807 transactions**
* **492 fraudulent transactions**
* **30 input features**
* **1 target variable (Class)**
### Features
The dataset contains:
* Time
* V1 through V28
* Amount
* Class
V1–V28 are anonymized PCA-transformed features provided by the original dataset.
### Class Distribution
| Class | Meaning | Transactions |
| ----: | ---------- | -----------: |
| 0 | Legitimate | 284,315 |
| 1 | Fraud | 492 |
Fraud represents only a small fraction of all transactions, making this a strongly imbalanced classification problem.
---
## 🧠 Machine Learning Pipeline
Credit Card Dataset
  ↓
Data Validation
  ↓
Train / Test Split
  ↓
Feature Scaling
  ↓
SMOTE on Training Data
  ↓
Random Forest Classifier
  ↓
Predictions
  ↓
Precision / Recall / F1 / ROC-AUC
  ↓
Streamlit Application
### Why SMOTE?
Because fraudulent transactions are heavily underrepresented, a model trained directly on the original distribution may favor the majority class.
**SMOTE (Synthetic Minority Over-sampling Technique)** creates synthetic minority-class training samples to improve the model's ability to identify fraud.
SMOTE is applied **only to the training set**, while the test set remains untouched.
This prevents data leakage during evaluation.
---
## 🌲 Model
The final model is:
**Random Forest Classifier + SMOTE**
Random Forest was selected because it:
* Handles nonlinear relationships
* Works well with tabular data
* Combines multiple decision trees
* Provides class probability estimates
* Performs well on complex classification problems
---
## 📈 Model Evaluation
Because fraud detection is an imbalanced classification problem, the project focuses on:
* **Precision**
* **Recall**
* **F1 Score**
* **ROC-AUC**
* **Confusion Matrix**
### Latest Model Results
The final evaluation results are stored in:
reports/model\_results.txt
Run the training script yourself to reproduce the latest metrics:
python train.py
The model is evaluated on an untouched test set after SMOTE is applied only to the training data.
---
## 🖥️ Streamlit Application
The project includes an interactive Streamlit dashboard.
### 🎲 Demo Mode
Demo Mode allows users to:
* Generate a random transaction
* Generate a legitimate transaction
* Generate a fraud transaction
* Analyze the transaction
* View fraud probability
* Compare the prediction with the known dataset label
This mode is intended for demonstration and testing.
### 📤 CSV Upload Mode
Users can upload a CSV containing the model's required input features.
The application:
1. Validates the input columns
2. Applies the saved preprocessing
3. Generates predictions
4. Calculates fraud probability
5. Displays the results
6. Provides a downloadable results CSV
---
##
The Kaggle dataset contains anonymized PCA features (V1–V28).
These are **not raw banking fields** that a user would normally enter manually.
Therefore, a real production system would require a feature-engineering pipeline that transforms raw transaction information into the same feature representation used during model training.
For this portfolio project, CSV Upload Mode assumes that the incoming data has already been transformed into the required feature format.
---
## 📁 Project Structure
Credit-Card-Fraud-Detection/
│
├── app.py
├── train.py
├── requirements.txt
├── sample\_transactions.csv
├── README.md
├── .gitignore
│
├── models/
│ ├── fraud\_model.pkl
│ └── scaler.pkl
│
├── reports/
│ └── model\_results.txt
│
├── dataset/
│ └── creditcard.csv
│
└── data/
  └── creditcard.csv
Large datasets and trained model files are excluded from GitHub using
.gitignore.
---
## ⚙️ Installation
### 1. Clone the repository
git clone <YOUR\_GITHUB\_REPOSITORY\_URL>
cd Credit-Card-Fraud-Detection
### 2. Create a virtual environment
Windows PowerShell:
python -m venv venv
### 3. Activate the environment
.\\venv\\Scripts\\Activate.ps1
### 4. Install dependencies
pip install -r requirements.txt
---
## 📥 Dataset Setup
Download the **Credit Card Fraud Detection dataset from Kaggle** and place the CSV in:
dataset/creditcard.csv
The dataset is intentionally excluded from this repository because of its size.
---
## 🧪 Train the Model
Run:
python train.py
The training script:
* Loads the dataset
* Splits training and testing data
* Scales Time and Amount
* Applies SMOTE to training data
* Trains Random Forest
* Calculates evaluation metrics
* Saves the trained model
* Saves the scaler
* Generates an evaluation report
Generated files:
models/fraud\_model.pkl
models/scaler.pkl
reports/model\_results.txt
---
##
Start the application:
streamlit run app.py
The application provides:
🎲 Demo Mode
📤 CSV Upload Mode
---
## 🛠️ Technologies Used
| Technology | Purpose |
| -------------------- | -------------------- |
| Python | Programming language |
| Pandas | Data processing |
| NumPy | Numerical operations |
| Scikit-learn | Machine learning |
| imbalanced-learn | SMOTE |
| Random Forest | Classification model |
| Joblib | Model serialization |
| Streamlit | Web application |
| Matplotlib / Seaborn | Data visualization |
---
## 🔍 Key Learning Outcomes
Through this project, I worked with:
* Data preprocessing
* Exploratory data analysis
* Imbalanced classification
* SMOTE
* Feature scaling
* Random Forest
* Model evaluation
* Precision vs Recall
* ROC-AUC
* Model serialization
* Streamlit deployment concepts
* CSV-based prediction pipelines
---
## 🚀 Future Improvements
Potential improvements include:
* Real-time transaction API
* Raw transaction feature engineering
* Advanced anomaly detection
* XGBoost / LightGBM comparison
* Threshold optimization
* Explainable AI using SHAP
* Model monitoring
* Database integration
* Real-time fraud alerts
* Production deployment
---
##
This project is an educational machine learning demonstration based on an anonymized Kaggle dataset.
It should **not** be used to make real financial or banking decisions without extensive validation, security controls, monitoring, and domain-specific testing.
---
## 👨💻 Author
**Shabarish Kandagatla**
Machine Learning / Data Analytics Project