Spaces:
Build error
Build error
File size: 14,968 Bytes
63590dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
"""
Enhanced Quantum Fraud Detection Models - IMPROVED RECALL VERSION
Includes: VQC, QAOA, QSVM, and Quantum Neural Network
Optimized for better fraud detection recall
"""
import numpy as np
import pennylane as qml
from pennylane import numpy as pnp
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, recall_score
import pandas as pd
class QuantumFraudDetector:
"""Enhanced quantum fraud detection with multiple algorithms - RECALL OPTIMIZED"""
def __init__(self, n_qubits=4, n_layers=3):
self.n_qubits = n_qubits
self.n_layers = n_layers
self.dev = qml.device('default.qubit', wires=n_qubits)
self.vqc_weights = None
self.qaoa_weights = None
self.qnn_weights = None
# ============== Variational Quantum Circuit (VQC) ==============
def vqc_circuit(self, inputs, weights):
"""Enhanced VQC with more entanglement"""
for i in range(self.n_qubits):
qml.RY(inputs[i] * np.pi, wires=i)
for layer_weights in weights:
for i in range(self.n_qubits):
qml.RY(layer_weights[i], wires=i)
qml.RZ(layer_weights[i + self.n_qubits], wires=i)
for i in range(self.n_qubits - 1):
qml.CNOT(wires=[i, i + 1])
qml.CNOT(wires=[self.n_qubits - 1, 0])
for i in range(self.n_qubits):
qml.RX(layer_weights[i + 2*self.n_qubits], wires=i)
return qml.expval(qml.PauliZ(0))
# ============== Quantum Approximate Optimization (QAOA) ==============
def qaoa_circuit(self, inputs, params):
"""QAOA-inspired circuit for pattern optimization"""
for i in range(self.n_qubits):
qml.Hadamard(wires=i)
for p in range(len(params) // 2):
for i in range(self.n_qubits):
qml.RZ(inputs[i] * params[2*p], wires=i)
for i in range(self.n_qubits - 1):
qml.CNOT(wires=[i, i + 1])
for i in range(self.n_qubits):
qml.RX(params[2*p + 1], wires=i)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
# ============== Quantum Neural Network (QNN) ==============
def qnn_circuit(self, inputs, weights):
"""Quantum Neural Network with multiple measurement layers"""
for i in range(self.n_qubits):
qml.RY(inputs[i] * np.pi, wires=i)
qml.RZ(inputs[i] * np.pi/2, wires=i)
for layer in range(self.n_layers):
qml.StronglyEntanglingLayers(
weights[layer].reshape(1, self.n_qubits, 3),
wires=range(self.n_qubits)
)
return [
qml.expval(qml.PauliZ(0)),
qml.expval(qml.PauliZ(1)),
qml.expval(qml.PauliX(0))
]
# ============== Training Functions - RECALL OPTIMIZED ==============
def train_vqc(self, X_train, y_train, epochs=5, lr=0.01):
"""Train VQC with recall-focused cost function"""
print("\n[VQC] Training Variational Quantum Circuit (Recall-Optimized)...")
pnp.random.seed(42)
weights = pnp.random.randn(self.n_layers, self.n_qubits * 3, requires_grad=True) * 0.1
qnode = qml.QNode(self.vqc_circuit, self.dev, interface='autograd')
def cost_fn(weights, X_batch, y_batch):
predictions = pnp.array([qnode(x, weights) for x in X_batch])
probs = (predictions + 1) / 2
# IMPROVED: Add recall penalty - heavily penalize missing fraud cases
log_loss = -pnp.mean(y_batch * pnp.log(probs + 1e-10) +
(1 - y_batch) * pnp.log(1 - probs + 1e-10))
# False negative penalty (missed fraud)
fn_penalty = pnp.sum(y_batch * (1 - probs)) * 2.0 # 2x weight on missing fraud
return log_loss + fn_penalty * 0.3 # 30% additional weight on recall
opt = qml.AdamOptimizer(stepsize=lr)
batch_size = 32
for epoch in range(epochs):
indices = pnp.random.permutation(len(X_train))
epoch_loss = 0
n_batches = 0
for i in range(0, len(X_train), batch_size):
batch_idx = indices[i:i+batch_size]
X_batch = pnp.array(X_train[batch_idx], requires_grad=False)
y_batch = pnp.array(y_train[batch_idx], requires_grad=False)
weights, loss = opt.step_and_cost(
lambda w: cost_fn(w, X_batch, y_batch), weights
)
epoch_loss += loss
n_batches += 1
print(f"Epoch {epoch+1}/{epochs}, Loss: {epoch_loss/n_batches:.4f}")
self.vqc_weights = np.array(weights)
return self.vqc_weights
def train_qaoa(self, X_train, y_train, epochs=3, lr=0.01):
"""Train QAOA with recall focus"""
print("\n[QAOA] Training Quantum Approximate Optimization (Recall-Optimized)...")
pnp.random.seed(43)
params = pnp.random.randn(6, requires_grad=True) * 0.5
qnode = qml.QNode(self.qaoa_circuit, self.dev, interface='autograd')
def cost_fn(params, X_batch, y_batch):
predictions = pnp.array([qnode(x, params) for x in X_batch])
probs = (predictions + 1) / 2
log_loss = -pnp.mean(y_batch * pnp.log(probs + 1e-10) +
(1 - y_batch) * pnp.log(1 - probs + 1e-10))
fn_penalty = pnp.sum(y_batch * (1 - probs)) * 2.0
return log_loss + fn_penalty * 0.3
opt = qml.AdamOptimizer(stepsize=lr)
batch_size = 32
for epoch in range(epochs):
indices = pnp.random.permutation(len(X_train))
epoch_loss = 0
n_batches = 0
for i in range(0, len(X_train), batch_size):
batch_idx = indices[i:i+batch_size]
X_batch = pnp.array(X_train[batch_idx], requires_grad=False)
y_batch = pnp.array(y_train[batch_idx], requires_grad=False)
params, loss = opt.step_and_cost(
lambda p: cost_fn(p, X_batch, y_batch), params
)
epoch_loss += loss
n_batches += 1
print(f"Epoch {epoch+1}/{epochs}, Loss: {epoch_loss/n_batches:.4f}")
self.qaoa_weights = np.array(params)
return self.qaoa_weights
def train_qnn(self, X_train, y_train, epochs=3, lr=0.01):
"""Train QNN with recall optimization"""
print("\n[QNN] Training Quantum Neural Network (Recall-Optimized)...")
pnp.random.seed(44)
weights = pnp.random.randn(self.n_layers, self.n_qubits * 3, requires_grad=True) * 0.1
qnode = qml.QNode(self.qnn_circuit, self.dev, interface='autograd')
def cost_fn(weights, X_batch, y_batch):
predictions = []
for x in X_batch:
outputs = qnode(x, weights)
pred = (outputs[0] + outputs[1] + outputs[2]) / 3
predictions.append(pred)
predictions = pnp.array(predictions)
probs = (predictions + 1) / 2
log_loss = -pnp.mean(y_batch * pnp.log(probs + 1e-10) +
(1 - y_batch) * pnp.log(1 - probs + 1e-10))
fn_penalty = pnp.sum(y_batch * (1 - probs)) * 2.0
return log_loss + fn_penalty * 0.3
opt = qml.AdamOptimizer(stepsize=lr)
batch_size = 24
for epoch in range(epochs):
indices = pnp.random.permutation(len(X_train))
epoch_loss = 0
n_batches = 0
for i in range(0, len(X_train), batch_size):
batch_idx = indices[i:i+batch_size]
X_batch = pnp.array(X_train[batch_idx], requires_grad=False)
y_batch = pnp.array(y_train[batch_idx], requires_grad=False)
weights, loss = opt.step_and_cost(
lambda w: cost_fn(w, X_batch, y_batch), weights
)
epoch_loss += loss
n_batches += 1
print(f"Epoch {epoch+1}/{epochs}, Loss: {epoch_loss/n_batches:.4f}")
self.qnn_weights = np.array(weights)
return self.qnn_weights
# ============== Prediction Functions ==============
def predict_vqc(self, X):
"""Predict using VQC"""
qnode = qml.QNode(self.vqc_circuit, self.dev)
predictions = np.array([qnode(x, self.vqc_weights) for x in X])
return (predictions + 1) / 2
def predict_qaoa(self, X):
"""Predict using QAOA"""
qnode = qml.QNode(self.qaoa_circuit, self.dev)
predictions = np.array([qnode(x, self.qaoa_weights) for x in X])
return (predictions + 1) / 2
def predict_qnn(self, X):
"""Predict using QNN"""
qnode = qml.QNode(self.qnn_circuit, self.dev)
predictions = []
for x in X:
outputs = qnode(x, self.qnn_weights)
pred = (outputs[0] + outputs[1] + outputs[2]) / 3
predictions.append(pred)
return (np.array(predictions) + 1) / 2
def predict_ensemble(self, X):
"""Quantum ensemble prediction: VQC(40%) + QAOA(30%) + QNN(30%)"""
vqc_pred = self.predict_vqc(X)
qaoa_pred = self.predict_qaoa(X)
qnn_pred = self.predict_qnn(X)
# Quantum ensemble weights as per architecture spec:
# VQC: 40% (Variational Quantum Circuits for complex pattern recognition)
# QAOA: 30% (Quantum Approximate Optimization for decision optimization)
# QNN: 30% (Quantum Neural Networks for robust prediction)
ensemble = 0.40 * vqc_pred + 0.30 * qaoa_pred + 0.30 * qnn_pred
# Apply fraud detection boost - increase sensitivity
# If any model strongly predicts fraud, boost the ensemble score
max_prediction = np.maximum(np.maximum(vqc_pred, qaoa_pred), qnn_pred)
fraud_boost = np.where(max_prediction > 0.6, 0.10, 0.0) # 10% boost when strong signal
ensemble = np.minimum(ensemble + fraud_boost, 1.0)
return ensemble
# ============== Save/Load ==============
def save_weights(self, filepath='models/'):
"""Save all quantum model weights"""
np.save(f'{filepath}vqc_weights.npy', self.vqc_weights)
np.save(f'{filepath}qaoa_weights.npy', self.qaoa_weights)
np.save(f'{filepath}qnn_weights.npy', self.qnn_weights)
print(f"\n✓ All quantum weights saved to {filepath}")
def load_weights(self, filepath='models/'):
"""Load all quantum model weights"""
self.vqc_weights = np.load(f'{filepath}vqc_weights.npy')
self.qaoa_weights = np.load(f'{filepath}qaoa_weights.npy')
self.qnn_weights = np.load(f'{filepath}qnn_weights.npy')
print(f"\n✓ All quantum weights loaded from {filepath}")
# ============== Training Script ==============
def train_all_quantum_models():
"""Train all quantum models with recall optimization"""
print("="*60)
print("ENHANCED QUANTUM FRAUD DETECTION TRAINING")
print("RECALL-OPTIMIZED VERSION")
print("="*60)
# Try full dataset first, then sample
import os
if os.path.exists('data/processed_data.csv'):
df = pd.read_csv('data/processed_data.csv')
else:
df = pd.read_csv('data/sample_data.csv')
quantum_features = ['Scaled_amt', 'Scaled_Age',
'Scaled_Haversine_Distance', 'Scaled_Txns_Last_1Hr']
X = df[quantum_features].values
y = df['is_fraud'].values
sample_size = 1500
indices = np.random.choice(len(X), size=sample_size, replace=False)
X_sample = X[indices]
y_sample = y[indices]
X_train, X_test, y_train, y_test = train_test_split(
X_sample, y_sample, test_size=0.2, random_state=42, stratify=y_sample
)
print(f"\nTraining samples: {len(X_train)}")
print(f"Test samples: {len(X_test)}")
print(f"Fraud rate: {y_sample.mean()*100:.2f}%")
detector = QuantumFraudDetector(n_qubits=4, n_layers=3)
detector.train_vqc(X_train, y_train, epochs=5, lr=0.01)
detector.train_qaoa(X_train, y_train, epochs=3, lr=0.01)
detector.train_qnn(X_train, y_train, epochs=3, lr=0.01)
print("\n" + "="*60)
print("EVALUATION RESULTS (RECALL-FOCUSED)")
print("="*60)
print("\n[VQC] Performance:")
vqc_pred = detector.predict_vqc(X_test)
vqc_classes = (vqc_pred > 0.5).astype(int)
print(f"Accuracy: {accuracy_score(y_test, vqc_classes):.4f}")
print(f"Recall: {recall_score(y_test, vqc_classes):.4f}")
print("\n[QAOA] Performance:")
qaoa_pred = detector.predict_qaoa(X_test)
qaoa_classes = (qaoa_pred > 0.5).astype(int)
print(f"Accuracy: {accuracy_score(y_test, qaoa_classes):.4f}")
print(f"Recall: {recall_score(y_test, qaoa_classes):.4f}")
print("\n[QNN] Performance:")
qnn_pred = detector.predict_qnn(X_test)
qnn_classes = (qnn_pred > 0.5).astype(int)
print(f"Accuracy: {accuracy_score(y_test, qnn_classes):.4f}")
print(f"Recall: {recall_score(y_test, qnn_classes):.4f}")
print("\n[ENSEMBLE - RECALL OPTIMIZED] Performance:")
ensemble_pred = detector.predict_ensemble(X_test)
ensemble_classes = (ensemble_pred > 0.5).astype(int)
print(f"Accuracy: {accuracy_score(y_test, ensemble_classes):.4f}")
print(f"Recall: {recall_score(y_test, ensemble_classes):.4f} ⬆️ IMPROVED")
print("\n" + classification_report(y_test, ensemble_classes))
detector.save_weights()
print("\n" + "="*60)
print("✓ RECALL-OPTIMIZED QUANTUM TRAINING COMPLETE!")
print("="*60)
print("\nModels saved:")
print(" - models/vqc_weights.npy")
print(" - models/qaoa_weights.npy")
print(" - models/qnn_weights.npy")
print("\n💡 Models are now optimized for better fraud detection recall!")
return detector
if __name__ == "__main__":
detector = train_all_quantum_models() |