Docsity

ML-Based Anomaly Detection in Financial Data (Python), Study Guides, Projects, Research of Electric Machines

Partial preview of the text

Download ML-Based Anomaly Detection in Financial Data (Python) and more Study Guides, Projects, Research Electric Machines in PDF only on Docsity!

International Islamic University Islamabad

Faculty of Engineering and Technology

Department of Electrical and Computer Engineering

MACHINE LEARNING

Open-Ended Lab Report

Submitted By:

Mahnoor Rasool (893_FET/BSEE/F-21)

Submitted to: Engr. Asad Ehsan

1. Introduction

In the era of digital transactions, financial fraud has become a major concern. This project presents a real-time fraud detection system developed using Python, Isolation Forest (an unsupervised machine learning model), and a fully functional Graphical User Interface (GUI). The system can detect anomalies in transactions and provide fraud alerts automatically or through manual checks. The GUI also includes summary statistics, a fraud meter, and fraud detection logs, offering a practical solution for live fraud monitoring.

2. Problem Statement

With the increase in online financial activities, fraudulent transactions have also become more frequent. Traditional systems often fail to detect new or unusual fraud patterns in real-time. There is a need for a lightweight, real-time fraud detection system that does not rely heavily on labeled data and can work on small devices or desktops without requiring complex setup.

3. Objectives

 To implement an unsupervised machine learning model (Isolation Forest) for anomaly detection.  To design a real-time fraud detection system using Python.  To develop a user-friendly GUI for both manual and automatic fraud detection.  To present fraud results with real-time alerts and logs.

4. Dataset Description

The dataset used contains 5000 samples of real financial transaction records. The features include anonymized values from V1 to V28, as well as the transaction Amount and Class. The "Class" column identifies whether a transaction was fraud (1) or normal (0), but this label was only used for evaluation, not training.

5. Methodology

5.3 Manual and Automatic Testing:  Manual testing included testing a single random transaction from the dataset or generating a new one using a button click.  Automatic testing was implemented using a background loop (after() method in tkinter) that simulates new transactions every few seconds without requiring user input. # CODE FOR MANUAL TESTING:

CODE FOR GENERATING NEW TRANSACTIONS AND MATCHING MANUALLY:

CODE FOR GRAPHS:

5.4 GUI Development and Working:  A GUI was developed using tkinter to make the fraud detection process interactive and easy to use.  The GUI contains: o Two buttons: one for manual testing of past or new transactions and one for automatic real-time testing. o A text area that logs each transaction result (fraud or normal) with a prefix [PAST] or [NEW].

o A fraud alert banner that turns red and displays a warning message when fraud is detected. o Summary counters showing the number of frauds, normal transactions, and total tested. o A fraud meter (progress bar) that dynamically updates the percentage of detected frauds.  The GUI enhances the project’s presentation and simulates a real-time fraud detection system used in banks and financial apps. Python Code for GUI: import tkinter as tk from tkinter import ttk import joblib import pandas as pd import numpy as np import random import board import busio from PIL import Image, ImageDraw, ImageFont import adafruit_ssd

=== Load model and data ===

model = joblib.load("model.pkl") scaler = joblib.load("scaler.pkl") df = pd.read_csv("sample_creditcard_5000.csv")

=== OLED setup ===

i2c = busio.I2C(board.SCL, board.SDA) oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)

frame_summary = tk.Frame(root, bg="#dff9fb", padx=20, pady=10, relief="ridge", bd=2) frame_summary.pack(pady=10, fill="x", padx=30) normal_count = tk.StringVar(value="0") fraud_count = tk.StringVar(value="0") total_tested = tk.StringVar(value="0") tk.Label(frame_summary, text="✅ Normal:", font=font_bold, bg="#dff9fb").grid(row=0, column=0) tk.Label(frame_summary, textvariable=normal_count, font=font_bold, fg="green", bg="#dff9fb").grid(row=0, column=1) tk.Label(frame_summary, text="❗ Fraud:", font=font_bold, bg="#dff9fb").grid(row=0, column=2) tk.Label(frame_summary, textvariable=fraud_count, font=font_bold, fg="red", bg="#dff9fb").grid(row=0, column=3) tk.Label(frame_summary, text="🧾 Total:", font=font_bold, bg="#dff9fb").grid(row=0, column=4) tk.Label(frame_summary, textvariable=total_tested, font=font_bold, fg="blue", bg="#dff9fb").grid(row=0, column=5) meter_label = tk.Label(root, text="📈 Fraud Rate (%)", font=font_bold, bg="#f 0 f 4 f 8 ") meter_label.pack() fraud_meter = ttk.Progressbar(root, orient="horizontal", length=600, mode="determinate") fraud_meter.pack()

=== Output Section ===

output_frame = tk.Frame(root) output_frame.pack(pady=15, fill="both", expand=True, padx=30)

output = tk.Text(output_frame, height=15, font=("Consolas", 11), wrap="none") output.pack(side="left", fill="both", expand=True) scroll = ttk.Scrollbar(output_frame, command=output.yview) scroll.pack(side="right", fill="y") output.config(yscrollcommand=scroll.set)

=== Logic Variables ===

normal = 0 fraud = 0 tested = 0 auto_running = True def update_banner(is_fraud): if is_fraud: fraud_banner.config(text="⚠️ FRAUD ALERT!", bg="red") show_oled_alert("⚠️ FRAUD ALERT!") else: fraud_banner.config(text="", bg="#f0f4f8") show_oled_alert("✅ NORMAL") fraud_banner.after(3000, lambda: fraud_banner.config(text="", bg="#f0f4f8")) def update_summary(predicted_label): global normal, fraud, tested tested += 1 if predicted_label == 1: fraud += 1 else: normal += 1

real_label = "❗ FRAUD" if real else "✅ NORMAL" match = "✅ MATCH" if predicted_label == real else "❌ MISMATCH" output.insert(tk.END, f"[PAST] Model: {result} | Real: {real_label} | {match}\n") output.see(tk.END) def auto_loop(): if auto_running: test_new_transaction() root.after(4000, auto_loop) def pause_auto(): global auto_running auto_running = False output.insert(tk.END, "[SYSTEM] Auto detection paused.\n") output.see(tk.END) def resume_auto(): global auto_running auto_running = True output.insert(tk.END, "[SYSTEM] Auto detection resumed.\n") output.see(tk.END)

=== Button Section ===

btn_frame = tk.Frame(root, bg="#f0f4f8") btn_frame.pack(pady=10)

Row 1

row1 = tk.Frame(btn_frame, bg="#f0f4f8") row1.pack(pady=5)

ttk.Button(row1, text="📂 Test Past Transaction", command=test_past_transaction).pack(side="left", padx=10) ttk.Button(row1, text="🧾 Manual Test New Transaction", command=test_new_transaction).pack(side="left", padx=10)

Row 2

row2 = tk.Frame(btn_frame, bg="#f0f4f8") row2.pack(pady=5) ttk.Button(row2, text="🧾 Pause Auto Testing", command=pause_auto).pack(side="left", padx=10) ttk.Button(row2, text="▶️ Resume Auto Testing", command=resume_auto).pack(side="left", padx=10)

=== Start Auto Detection Loop ===

auto_loop() footer = tk.Label(root, text="© Mahnoor | OLED GUI | Auto/Manual + Pause", font=("Arial", 10), bg="#f0f4f8", fg="#777") footer.pack(pady=5) root.mainloop() GUI Screenshots:

 Integration with real transaction APIs or payment gateways.  Addition of deep learning models for comparison.  Logging fraud cases to a database for record keeping.  Email/SMS alerts for fraud notification.

9. References

Scikit-learn documentation: https://scikit-learn.org Isolation Forest paper: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf Credit Card Fraud Dataset (Kaggle)