File size: 2,052 Bytes
47f01a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import torch
import torch.nn as nn
from flask import Flask, request, jsonify
from sklearn.preprocessing import MinMaxScaler
import joblib

# Define the autoencoder model
class Autoencoder(nn.Module):
    def __init__(self, input_dim):
        super(Autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, 64),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            nn.Dropout(0.2)
        )
        self.decoder = nn.Sequential(
            nn.Linear(64, input_dim),
            nn.BatchNorm1d(input_dim),
            nn.Sigmoid()
        )

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

# Load trained model
input_dim = 29  # Assuming 29 features (V1-V28 + Amount)
model = Autoencoder(input_dim)
model.load_state_dict(torch.load("trained_autoencoder.pth"))
model.eval()

# Load the MinMaxScaler
scaler = joblib.load("scaler.pkl")

# Create Flask app
app = Flask(__name__)

@app.route('/')
def home():
    return "Credit Card Fraud Detection API is Running!"

@app.route('/predict', methods=['POST'])
def predict():
    try:
        # Get JSON input
        data = request.get_json()
        X_input = np.array(data['features']).reshape(1, -1)  # Ensure it's in the right shape

        # Scale input data
        X_scaled = scaler.transform(X_input)

        # Convert to PyTorch tensor
        X_tensor = torch.tensor(X_scaled, dtype=torch.float32)

        # Get reconstruction error
        recon = model(X_tensor).detach().numpy()
        recon_error = np.mean((recon - X_scaled) ** 2)

        # Use threshold to classify as fraud (1) or normal (0)
        threshold = 0.01  # Adjust this based on previous experiments
        prediction = 1 if recon_error > threshold else 0

        return jsonify({'fraud_probability': float(recon_error), 'is_fraud': prediction})
    
    except Exception as e:
        return jsonify({'error': str(e)})

if __name__ == '__main__':
    app.run(debug=True)