File size: 5,172 Bytes
3c7592d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import json
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix, classification_report
from torch_geometric.data import Data
from gnn_aml import GAT, prepare_graph
from graph_aml import detect_pattern

# Load Model
print("πŸ” Loading Trained Model...")
model = GAT(num_node_features=3, hidden_dim=16, output_dim=2)
model.load_state_dict(torch.load("trained_model.pth"))
model.eval()

# Load New Test Data
print("πŸ“₯ Loading New Test Transactions...")
with open("test_transactions.json", "r") as f:
    test_transactions = json.load(f)

# Prepare Graph Data
print("πŸ”„ Preparing Test Graph Data...")
test_graph, _ = prepare_graph()

# Run Model Predictions
print("🧠 Running Predictions...")
with torch.no_grad():
    output = model(test_graph)
    probs = torch.softmax(output, dim=1)  # Convert logits to probabilities
    predictions = (probs[:, 1] > 0.75).long()  # 1 = AML, 0 = Normal

# Store predictions
test_results = []
y_true = []  # True labels
y_pred = []  # Predicted labels

for txn, prediction in zip(test_transactions, predictions):
    risk_score = txn["RiskScore"]
    true_label = 1 if txn["AML_Flag"] == 1 else 0  # True AML label
    predicted_label = prediction.item()

    # Update labels for confusion matrix
    y_true.append(true_label)
    y_pred.append(predicted_label)

    if risk_score < 0.5:
        predicted_pattern = "None"
    elif predicted_label == 1:
        predicted_pattern = detect_pattern(test_graph)
    else:
        predicted_pattern = "None"

    test_results.append({
        "TransactionID": txn["TransactionID"],
        "TrueLabel": true_label,
        "PredictedLabel": predicted_label,
        "PredictedPattern": predicted_pattern,
        "RiskScore": risk_score
    })

# Save results to file
with open("new_test_results_v2.json", "w") as f:
    json.dump(test_results, f, indent=4)

# **βœ… Compute Accuracy Metrics**
print("\nπŸ“Š **Final Test Results:**")
cm = confusion_matrix(y_true, y_pred)
report = classification_report(y_true, y_pred, target_names=[
                               "Normal", "AML"], digits=4)

print("\nπŸ”’ **Confusion Matrix:**\n", cm)
print("\nπŸ“„ **Classification Report:**\n", report)

# **βœ… Plot Confusion Matrix**
plt.figure(figsize=(6, 5))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=[
            "Normal", "AML"], yticklabels=["Normal", "AML"])
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()

# **βœ… Plot Prediction Distribution**
labels, counts = np.unique(y_pred, return_counts=True)
plt.figure(figsize=(6, 5))
plt.bar(["Normal", "AML"], counts, color=["green", "red"])
plt.xlabel("Transaction Classification")
plt.ylabel("Number of Transactions")
plt.title("AML vs. Normal Transactions Detected")
plt.show()

print("βœ… Accuracy analysis complete! Check charts & logs.")


# import torch
# import json
# from torch_geometric.data import Data
# from gnn_aml import GAT, prepare_graph
# from graph_aml import detect_pattern

# # Load Model
# print("πŸ” Loading Trained Model...")
# model = GAT(num_node_features=3, hidden_dim=16, output_dim=2)
# model.load_state_dict(torch.load("trained_model.pth"))
# model.eval()

# # Load New Test Data
# print("πŸ“₯ Loading New Test Transactions...")
# with open("test_transactions.json", "r") as f:
#     test_transactions = json.load(f)

# # Prepare Graph Data
# print("πŸ”„ Preparing Test Graph Data...")
# test_graph, _ = prepare_graph()

# # Run Model Predictions
# print("🧠 Running Predictions...")
# with torch.no_grad():
#     output = model(test_graph)
#     probs = torch.softmax(output, dim=1)  # Convert logits to probabilities
#     predictions = (probs[:, 1] > 0.75).long()  # 1 = AML, 0 = Normal

# # Store predictions
# test_results = []
# aml_count = 0
# normal_count = 0

# for txn, prediction in zip(test_transactions, predictions):
#     risk_score = txn["RiskScore"]
#     predicted_label = prediction.item()

#     if risk_score < 0.5:
#         predicted_pattern = "None"  # βœ… Mark as safe
#         normal_count += 1  # βœ… Count normal transactions
#     elif predicted_label == 1:
#         predicted_pattern = detect_pattern(
#             test_graph)  # βœ… Detect actual pattern
#         aml_count += 1  # βœ… Count AML transactions
#     else:
#         predicted_pattern = "None"
#         normal_count += 1  # βœ… Count normal transactions

#     test_results.append({
#         "TransactionID": txn["TransactionID"],
#         "PredictedPattern": predicted_pattern,
#         "RiskScore": risk_score
#     })

# # **βœ… Move logging here, after results are fully analyzed**
# print("\nπŸ“Š **Final Test Results:**")
# print(f"πŸ”΄ AML Detected: {aml_count}")
# print(f"🟒 Normal Transactions: {normal_count}")

# # Save results to file
# with open("new_test_results_v2.json", "w") as f:
#     json.dump(test_results, f, indent=4)

# print("βœ… Test results saved to `new_test_results_v2.json`")