1.
Abstract
The unauthorized purchase and misuse of controlled substances pose
significant risks to public health and regulatory compliance. Existing systems
rely on manual identity verification and static rule-based monitoring, making
them vulnerable to identity fraud, human error, and ineffective quota
enforcement. This project proposes a machine learning–based secure identity
verification and quota enforcement system to regulate controlled substance
purchases in real time.
The system analyzes transactional and identity-related data, including
user attributes, purchase history, temporal patterns, and behavioral features.
Machine learning models are used to verify user identity, detect abnormal
purchasing behavior, and identify attempts to bypass purchase limits. Based on
this analysis, the system dynamically enforces purchase quotas and flags
suspicious transactions.
By adopting an adaptive, data-driven approach, the proposed system
enhances verification accuracy, reduces fraudulent purchases, minimizes
reliance on manual supervision, and improves transparency and regulatory
compliance in controlled substance distribution.
1
2. Objective
The primary objective of this project is to design an integrated machine
learning–based system for secure identity verification and quota enforcement in
controlled substance purchases. The system aims to verify user identity using
ML-based behavioral analysis to prevent impersonation and unauthorized
access. It seeks to detect abnormal purchasing behavior through anomaly
detection models to identify misuse patterns early. Another objective is to
dynamically enforce purchase quotas in real time to prevent over-purchasing
and repeated misuse. Finally, the system aims to ensure privacy, transparency,
and regulatory compliance through secure data handling and audit logging.
2
3. Literature Review
[1] M. Pevnick et al., “Detecting Drug Diversion in Health-System Data Using
Machine Learning,” Journal of the American Medical Informatics Association
(JAMIA), 2019.
This paper presents a machine learning–based approach to detect drug
diversion in healthcare systems using prescription and transaction data. The
authors apply supervised learning models to identify abnormal usage patterns
related to controlled substances. The study demonstrates how ML techniques
can support compliance monitoring and early detection of misuse in regulated
environments. The work highlights the importance of data-driven monitoring
for preventing illegal or excessive access to controlled substances.
Pros:
Focuses on controlled substances and regulated domains
Uses machine learning for misuse and diversion detection
Supports compliance monitoring and audit processes
Cons:
Does not include identity verification mechanisms
Lacks real-time quota enforcement logic
Focuses mainly on detection rather than prevention
3
[2] A. Ali, A. Aibinu, S. Mustapha, and N. Abdullah, “Machine Learning for
Fraud Detection in Healthcare: A Systematic Review,” Applied Sciences, 2022.
This paper reviews machine learning techniques used for fraud detection
in healthcare systems. It discusses supervised and unsupervised models for
identifying abnormal transaction behavior and misuse patterns. The study
emphasizes anomaly detection as a key component in preventing fraudulent
activities. The methods discussed are applicable to identifying over-purchase
and abnormal usage in regulated systems.
Pros
Covers ML-based anomaly detection techniques
Applicable to regulated and healthcare-related systems
Reduces dependency on manual monitoring
Cons
High false positives in sparse datasets
Requires continuous model retraining
Does not integrate identity verification
4
[3] M. Al-Hassan and S. Roy,“Anomaly Detection in Purchase Behavior Using
Machine Learning,” International Journal of Information Security, 2023.
This study focuses on detecting abnormal purchasing behavior using ML-
based anomaly detection techniques. By learning normal transaction patterns,
the system identifies deviations such as excessive purchases, unusual frequency,
and suspicious timing. The approach is effective in preventing misuse and fraud
in regulated product sales.
Pros
Effective detection of abnormal purchase behavior
Reduces dependency on manual monitoring
Suitable for misuse detection in purchase systems
Cons
High false positives in sparse data
Limited real-time enforcement
Does not include identity verification
5
[4] Md Morshedul Islam and Md Abdur Rafiq, “Privacy Preserving Machine
Learning for Behavioral Authentication Systems,” arXiv, 2023.
This paper proposes privacy-preserving machine learning models for behavioral
authentication. The system uses user behavior patterns to verify identity while
minimizing exposure of sensitive data. The study highlights the importance of
secure data handling and anonymization in authentication systems. It provides
insights into implementing secure identity verification using ML.
Pros:
Enhances security through behavior-based authentication
Supports privacy-preserving ML techniques
Reduces reliance on traditional credentials
Cons:
Sensitive to behavioral changes
Does not address quota enforcement
Not designed for regulated purchase systems
6
[5] Chuo Jun Zhang, Asif Q. Gill, Bo Liu, and Memoona J. Anwar, “AI-based
Identity Fraud Detection: A Systematic Review,” arXiv, 2025.
This systematic review analyzes various AI and machine learning
techniques used for identity fraud detection across digital systems. The paper
categorizes identity verification approaches based on behavioral analysis,
biometric data, and transaction patterns. It also discusses challenges such as
data privacy, model explainability, and scalability. The review provides a strong
theoretical foundation for applying ML to secure identity verification.
Pros:
Comprehensive overview of ML-based identity verification methods
Identifies challenges and trends in identity fraud detection
Supports risk-based and behavior-based authentication models
Cons:
Does not address controlled substance purchase scenarios
No quota enforcement or regulatory compliance discussion
Focuses on detection rather than enforcement
7
[6] M. Misbahuddin, B. S. Bindhumadhava et al., “Design of a Risk-Based
Authentication System Using Machine Learning Techniques,” IEEE, 2017.
This paper proposes a risk-based authentication system that applies machine
learning techniques to evaluate user legitimacy based on behavioral and
contextual information. The system models user behavior using features such as
access history, location, and usage patterns to compute a dynamic risk score
during authentication. Machine learning classifiers are employed to distinguish
between legitimate and suspicious users, enabling adaptive authentication
decisions. The study demonstrates improved security compared to static
authentication mechanisms by continuously assessing risk rather than relying on
fixed credentials.
Pros:
Implements machine learning–based risk assessment
Uses behavioral patterns for adaptive authentication
Improves security over static authentication systems
Cons:
Limited to authentication scenarios only
Does not address transaction monitoring or anomaly detection
Lacks quota enforcement or regulatory control mechanisms
8
[7] A. Herreros-Martínez, R. Magdalena-Benedicto et al., “Applied Machine
Learning to Anomaly Detection in Enterprise Purchase Processes,” arXiv, 2024.
This paper presents a machine learning–based anomaly detection
framework for identifying abnormal behavior in enterprise purchase processes.
The authors analyze real-world, unlabeled purchase datasets and apply
unsupervised learning techniques such as clustering and Isolation Forest to
detect unusual purchasing patterns. The approach demonstrates improved
detection accuracy compared to rule-based audit systems and highlights the
effectiveness of data-driven analysis in identifying potential policy violations.
The study emphasizes post-transaction anomaly identification in large-scale
purchase environments.
Pros:
Focuses on purchase and transaction data analysis
Applies machine learning for anomaly detection
Works effectively on real-world unlabeled datasets
Cons:
Operates mainly in post-purchase analysis
Does not include identity verification mechanisms
Lacks real-time quota enforcement functionality
9
4. Existing System
The existing system for controlled substance monitoring relies on
fragmented approaches where identity verification, purchase tracking, and
misuse detection operate independently. Most systems use basic authentication
methods such as manual ID checks or static credentials, which are insufficient
to prevent impersonation or repeated misuse. Anomaly detection techniques are
often applied only after transactions are completed, leading to delayed
identification of suspicious behavior. Purchase limits are enforced using fixed
rules or manual audits, making real-time prevention difficult. Additionally,
existing systems focus more on detection rather than proactive enforcement,
allowing misuse to occur before corrective action is taken.
4.1 Demerits of Existing System:
The existing system lacks an integrated framework that combines identity
verification, anomaly detection, and quota enforcement. It depends heavily on
static rules and historical audits, which limits adaptability to evolving misuse
patterns. High false positives in anomaly detection result in unnecessary
restrictions on genuine users. The absence of real-time enforcement allows
quota violations before detection. Moreover, limited privacy-preserving
mechanisms and poor explainability of ML decisions reduce system trust and
regulatory acceptance.
10
5. Problem Statement
Existing research demonstrates the effectiveness of machine learning in identity
verification, anomaly detection, and compliance monitoring. However, these
approaches are mostly implemented as independent systems, addressing only a
single aspect of misuse prevention. Identity verification methods focus on
detecting fraudulent users but do not enforce purchase limits. Anomaly
detection techniques identify abnormal behavior but lack real-time enforcement
mechanisms. Compliance monitoring systems detect misuse after it occurs
rather than preventing it at the transaction level. As a result, controlled
substance purchases remain vulnerable to repeated misuse, quota violations, and
delayed intervention. Therefore, there is a need for an integrated ML-based
system that securely verifies user identity, detects abnormal behavior, and
enforces purchase quotas in real time for controlled substance purchases.
11
6. Proposed System
The proposed system uses machine learning to enhance identity verification and
enforce purchase limits for controlled substances. It includes:
Supervised machine learning models for secure identity verification and
eligibility classification
Unsupervised anomaly detection techniques to identify abnormal or
suspicious purchase behaviour
Dynamic quota enforcement based on user history and risk assessment
Privacy protection through anonymized data storage and secure hashing
mechanisms
Administrative dashboard with audit logs for real-time monitoring and
regulatory compliance
This ML-based approach enables real-time enforcement, adaptive decision-
making, and reduced dependence on manual and static rule-based systems.
12
7. System Specifications
7.1 Hardware Requirements:
Processor: Intel Core i5 or above
RAM: Minimum 8 GB
Storage: 500 GB or higher
GPU: Optional (recommended for faster model training)
7.2 Software Requirements:
Programming Language: Python (3.x)
Machine Learning Libraries: Scikit-learn, Pandas, NumPy
Web Backend Framework: Flask / FastAPI
Frontend Framework: React / Streamlit
Database: SQLite / PostgreSQL
Visualization Tools: Matplotlib / Power BI
7.3 Software description:
The system is developed using Python (3.x) as the primary programming
language due to its simplicity and strong support for machine learning. Scikit-
learn, Pandas, and NumPy are used for data preprocessing, model training, and
performance evaluation. The backend of the application is implemented using
Flask or FastAPI to handle user requests and model inference. The frontend
interface is built using React or Streamlit to provide an interactive and user-
friendly experience. SQLite or PostgreSQL is used for secure data storage and
management. Matplotlib and Power BI are used for visualizing data trends and
model results. A GPU is optional and can be used to speed up model training.
13
8. Overall DataFlow Diagram
14
9. NUMBER OF MODULES
1. Dataset Preparation & Preprocessing Module
Collects and structures user identity, transaction, and behavioral data. Cleans,
encodes, and scales features to produce ML-ready datasets for reliable model
training.
2. Model Training & Decision Logic Module
Trains ML models for identity verification and anomaly detection. Combines
model outputs to generate approve, flag, or block decisions.
3. Backend Development Module
Implements secure server-side APIs to process purchase requests. Integrates ML
predictions with quota enforcement and validation logic.
4. System Integration Module
Connects frontend, backend, ML models, and database components. Enables
real-time data flow, decision processing, and scalable operation.
5. Secure Audit & Logging Module
Records transactions and system actions securely. Ensures privacy-preserving
storage, auditability, and regulatory compliance.
6. Testing & Validation Module
Evaluates model accuracy and anomaly detection performance. Validates system
behavior under normal and misuse scenarios to ensure robustness.
15
10. MODULE IMPLEMENTATION
MODULE 1: Dataset Preparation and Preprocessing Module
This module is responsible for preparing behavioral and transactional
data used in controlled substance purchase analysis. It processes user identity
attributes, purchase history, and time-based transaction data to ensure
consistency and reliability. Raw records often contain missing values, noise, and
categorical information unsuitable for machine learning models. The module
performs data cleaning, normalization, feature extraction, and transformation to
convert raw inputs into structured features. Behavioral indicators such as
purchase frequency, last purchase gap, night purchase flag, and repeated attempt
flag are derived to capture user behavior patterns. The final output is a
standardized dataset suitable for identity verification and anomaly detection
models.
The preprocessing module is designed as a structured pipeline with
clearly defined stages: data ingestion, cleaning, transformation, feature
engineering, and scaling. Each stage refines the data incrementally to improve
quality and learning effectiveness. Feature engineering is placed after cleaning
to ensure accurate behavioral pattern extraction. Encoding and scaling are
applied as the final step to maintain uniform feature representation. The
modular design ensures reusability, clarity, and easy extension for additional
features or regulatory constraints
The module is implemented using Python libraries such as Pandas,
NumPy, and Scikit-learn. The dataset is loaded from CSV format and validated
for schema consistency. Missing values and inconsistent entries are handled
using conditional filtering and statistical methods. Categorical attributes such as
gender, region, and substance type are label-encoded, while numerical attributes
are normalized using standard scaling.
16
MODULE 2: Model Training and Decision Logic Module
This module focuses on learning user behavior patterns and generating
system decisions using machine learning techniques. A supervised classification
model is used for identity verification, while an unsupervised anomaly detection
model identifies suspicious purchase behavior. The identity model learns
legitimate user behavior from historical patterns, while the anomaly model
detects deviations that indicate misuse or quota bypass attempts. Model outputs
are combined through decision logic to generate final outcomes such as
approve, flag, or block.
The module is designed as a dual-model architecture consisting of an
identity verification layer and an anomaly detection layer. Outputs from both
layers are integrated through a decision logic component to support risk-aware
decision making. This separation improves robustness by ensuring identity
validation and behavior analysis operate independently. The design allows
flexible tuning of risk thresholds and easy replacement of models without
affecting the overall system flow.
The module is implemented using Scikit-learn. The dataset is split into
training and testing sets using stratified sampling. A supervised classifier is
trained to predict identity verification outcomes. Isolation Forest is implemented
for anomaly detection without requiring labeled fraud data. Model performance
is evaluated using accuracy, precision, recall, and confusion matrices. Final
decision logic combines identity verification results and anomaly flags to
generate system decisions.
17
11. SAMPLE CODE
# 1. Import libraries
import pandas as pd
from [Link] import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import IsolationForest
# 2. Load dataset
df = pd.read_csv("controlled_substance_dataset.csv")
# 3. Prepare targets
y_identity = df["identity_verified"]
y_anomaly = df["anomaly_flag"]
# 4. Prepare features
X = [Link](["identity_verified", "anomaly_flag", "user_id"], axis=1)
18
# Encode categorical features
categorical_cols = ["gender", "region", "substance_type", "day_of_week"]
encoder = LabelEncoder()
for col in categorical_cols:
X[col] = encoder.fit_transform(X[col])
# Scale data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 5. Train Identity Verification Model
X_train_id, X_test_id, y_train_id, y_test_id = train_test_split(
X_scaled, y_identity, test_size=0.2, stratify=y_identity
identity_model = LogisticRegression(max_iter=1000)
identity_model.fit(X_train_id, y_train_id)
# 6. Train Anomaly Detection Model
iso_forest = IsolationForest(contamination=0.2, random_state=42)
iso_forest.fit(X_scaled)
19
# 7. Dynamic Quota Enforcement Function
def dynamic_quota_enforcement(requested_qty, avg_monthly, identity_ok,
anomaly, remaining):
if identity_ok == 0:
return "BLOCKED"
allowed = avg_monthly * 0.5 if anomaly == 1 else avg_monthly
allowed = min(allowed, remaining)
return "APPROVED" if requested_qty <= allowed else "BLOCKED"
# 8. Apply Final Decision
df["final_decision"] = [Link](
lambda row: dynamic_quota_enforcement(
row["quantity_requested"],
row["avg_monthly_purchase"],
row["identity_verified"],
row["anomaly_flag"],
row["avg_monthly_purchase"]
),
axis=1
print(df["final_decision"].value_counts())
20
12. SNAPSHOTS
Figure 1
Figure 2
21
Figure 3
Figure 4
22
13. REFERENCE PAPERS
[1] M. Pevnick et al., “Detecting Drug Diversion in Health-System Data Using
Machine Learning,” Journal of the American Medical Informatics Association
(JAMIA), 2019.
[2] A. Ali, A. Ajibinu, S. Mustafa and N. Abdullah, “Machine Learning for
Fraud Detection in Healthcare: A Systematic Review,” Applied Sciences, 2022.
[3] M. Al-Hassan and S. Roy, “Anomaly Detection in Purchase Behavior Using
Machine Learning,” International Journal of Information Security, 2023.
[4] Md. Morshedul Islam and Md. Abdur Rafiq, “Privacy Preserving Machine
Learning for Behavioral Authentication Systems,” arXiv preprint, 2023.
[5] Chuo Jun Zhang, Asif Q. Gill, Bo Liu and Memon A. Anwar, “AI-Based
Identity Fraud Detection: A Systematic Review,” arXiv preprint, 2025.
[6] M. Mishbahuddin, B. S. Bindhumadhava et al., “Design of a Risk-Based
Authentication System Using Machine Learning Techniques,” IEEE, 2017.
[7] A. Herreros-Martinez, R. Magdalena-Benedicto et al., “Applied Machine
Learning to Anomaly Detection in Enterprise Purchase Processes,” arXiv
preprint, 2024.
23