Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1222 lines (990 loc) · 42.1 KB
/
Copy pathapp.py
File metadata and controls
1222 lines (990 loc) · 42.1 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Dashboard for the malware classification project.
Shows all the results from the notebooks in one place.
"""
import streamlit as st
import pandas as pd
import numpy as np
import json
from pathlib import Path
# where our files live
BASE = Path(__file__).parent
RESULTS = BASE / "results"
DATASET = BASE / "dataset"
# page setup
st.set_page_config(
page_title="Malware Detection Results",
layout="wide"
)
# helper functions
def load_json(name):
"""grab a json file from results folder"""
path = RESULTS / name
if path.exists():
with open(path) as f:
return json.load(f)
return None
def show_image(name):
"""load image as bytes and display it"""
path = RESULTS / name
if path.exists():
with open(path, "rb") as f:
img_bytes = f.read()
st.image(img_bytes, use_container_width=True)
else:
st.warning(f"Image not found: {name}")
def get_errors(confusion_matrix):
"""pull out false positives and negatives"""
fp = confusion_matrix[0][1]
fn = confusion_matrix[1][0]
return fp, fn
def load_dataset():
"""load the processed dataset for live stats"""
path = DATASET / "processed_dataset.csv"
if path.exists():
return pd.read_csv(path)
return None
# load all model results at startup
results = {
"linear": load_json("linear_regression_results.json"),
"logistic": load_json("logistic_regression_results.json"),
"naive_bayes": load_json("naive_bayes_results.json"),
"random_forest": load_json("random_forest_results.json"),
"xgboost": load_json("xgboost_results.json")
}
# sidebar nav
st.sidebar.title("Navigation")
page = st.sidebar.radio(
"Go to",
["Home", "Dataset", "Compare Models", "Linear Regression",
"Logistic Regression", "Naive Bayes", "Random Forest",
"XGBoost", "Hardware", "Notebooks"]
)
# home page
if page == "Home":
st.title("Memory-Based Malware Detection")
st.markdown("**Machine Learning Analysis of the CIC-MalMem-2022 Dataset**")
st.divider()
# quick stats row
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Total Samples", "58,596")
c2.metric("Raw Features", "56")
c3.metric("Selected Features", "30")
c4.metric("Best Accuracy", "100%")
c5.metric("Models Tested", "5")
st.divider()
# intro section
left, right = st.columns([3, 2])
with left:
st.subheader("Project Overview")
st.markdown("""
This project applies machine learning to **memory forensics** for malware detection.
Instead of scanning files on disk (which malware can easily disguise through packing
or obfuscation), we analyze **runtime memory dumps** to catch malicious behavior.
**The Core Idea:**
- Malware must execute to cause damage
- Executing code leaves behavioral traces in memory
- These traces are captured by the Volatility Framework
- ML models learn to distinguish malware patterns from normal behavior
**Key Discovery:**
The single most discriminative feature is `svcscan.shared_process_services` -
malware creates **1,550x more** shared process services than benign software.
This is because malware commonly uses Windows services for persistence.
""")
st.subheader("Methodology")
st.markdown("""
| Step | Description |
|------|-------------|
| 1. Data Collection | CIC-MalMem-2022 dataset - 58k memory dumps |
| 2. Feature Extraction | Volatility Framework extracts 56 behavioral features |
| 3. Preprocessing | RobustScaler normalization + chi-squared feature selection |
| 4. Model Training | 5 algorithms: Linear, Logistic, Naive Bayes, Random Forest, XGBoost |
| 5. Evaluation | 5-fold stratified cross-validation + held-out test set |
""")
with right:
st.subheader("Model Performance")
# build comparison table from results
if any(results.values()):
rows = []
for key, data in results.items():
if data:
cm = data.get("confusion_matrix", [[0,0],[0,0]])
fp, fn = get_errors(cm)
rows.append({
"Model": data.get("model", key),
"Accuracy": f"{data['test_accuracy']*100:.2f}%",
"Errors": fp + fn
})
df_results = pd.DataFrame(rows)
st.dataframe(df_results, hide_index=True, use_container_width=True)
st.success("**Winner:** Random Forest with 100% accuracy (0 errors)")
st.subheader("Why Memory Analysis Works")
st.markdown("""
| Approach | Evasion Difficulty |
|----------|-------------------|
| File signatures | Easy - change a few bytes |
| Heuristics | Medium - mimic normal behavior |
| **Memory forensics** | **Hard - must execute to attack** |
Memory analysis catches what malware **does**, not what it **looks like**.
""")
st.divider()
# comparison with prior work
st.subheader("Comparison with Prior Work")
st.markdown("""
| Study | Method | Accuracy | Our Improvement |
|-------|--------|----------|-----------------|
| Carrier et al. (2022) | RF + Feature Engineering | 99.2% | +0.8% |
| Shamshad et al. (2023) | DNN + ANOVA | 99.0% | +1.0% |
| Cevallos-Salas (2023) | CNN + Memory | 98.5% | +1.5% |
| Hossain (2024) | Ensemble + Adversarial | 98.8% | +1.2% |
| **This Work** | **RF / XGBoost** | **100%** | **Baseline** |
**Key Differences:** Chi-squared feature selection (top 30), RobustScaler normalization,
5-fold stratified CV confirming 99.99% generalization.
""")
st.divider()
# key findings section
st.subheader("Key Findings")
c1, c2, c3 = st.columns(3)
with c1:
st.markdown("**Top Discriminative Features**")
st.markdown("""
1. `shared_process_services` - 1,550x difference
2. `nservices` - total service count
3. `kernel_drivers` - driver registrations
4. `nevent` - event handle count
5. `nprocs64bit` - 64-bit process count
Service manipulation dominates - malware creates
services for persistence and privilege escalation.
""")
with c2:
st.markdown("**Model Insights**")
st.markdown("""
- Even linear regression achieves 99.34%
- This indicates near-linear class separability
- Random Forest's 100% suggests possible overfitting
- Cross-validation confirms consistency
- All models agree on feature importance
The data is "easy" due to strong behavioral differences.
""")
with c3:
st.markdown("**Limitations**")
st.markdown("""
- Lab-generated samples (not wild malware)
- Perfect accuracy raises overfitting concerns
- Dataset from 2022 - patterns may evolve
- No adversarial samples tested
- Single dataset - needs external validation
Real-world deployment requires continuous updates.
""")
# dataset page
elif page == "Dataset":
st.title("Dataset Analysis")
st.markdown("**CIC-MalMem-2022: Memory Forensics Dataset**")
st.divider()
# load actual data for live stats
df = load_dataset()
# overview metrics
c1, c2, c3, c4, c5 = st.columns(5)
if df is not None:
c1.metric("Total Samples", f"{len(df):,}")
c2.metric("Benign", f"{(df['binary']=='Benign').sum():,}")
c3.metric("Malware", f"{(df['binary']=='Malware').sum():,}")
c4.metric("Features", f"{len([c for c in df.columns if c not in ['binary','category','family','variant']])}")
c5.metric("Balance", "50/50")
st.divider()
left, right = st.columns(2)
with left:
st.subheader("Dataset Properties")
st.markdown("""
| Property | Value |
|----------|-------|
| Source | Canadian Institute for Cybersecurity |
| Year | 2022 |
| Collection Method | Memory dumps from VMs |
| Feature Extraction | Volatility Framework |
| Original Features | 56 |
| After Zero-Variance Removal | 53 |
| After Chi-Squared Selection | 30 |
| Train/Test Split | 80% / 20% (stratified) |
""")
st.subheader("Malware Categories")
if df is not None:
cat_counts = df['category'].value_counts()
st.markdown(f"""
| Category | Count | Percentage |
|----------|-------|------------|
| Benign | {cat_counts.get('Benign', 0):,} | {cat_counts.get('Benign', 0)/len(df)*100:.1f}% |
| Trojan | {cat_counts.get('Trojan', 0):,} | {cat_counts.get('Trojan', 0)/len(df)*100:.1f}% |
| Ransomware | {cat_counts.get('Ransomware', 0):,} | {cat_counts.get('Ransomware', 0)/len(df)*100:.1f}% |
| Spyware | {cat_counts.get('Spyware', 0):,} | {cat_counts.get('Spyware', 0)/len(df)*100:.1f}% |
""")
with right:
st.subheader("Class Distribution")
show_image("class_distribution.png")
st.divider()
# feature details
st.subheader("Feature Categories (Volatility Plugins)")
c1, c2, c3 = st.columns(3)
with c1:
st.markdown("**Process Analysis**")
st.markdown("""
`pslist` / `psxview` plugins:
- `nproc` - running process count
- `nppid` - parent process IDs
- `avg_threads` - threads per process
- `avg_handlers` - handlers per process
*Malware often spawns hidden processes or injects into legitimate ones.*
""")
st.markdown("**DLL Analysis**")
st.markdown("""
`dlllist` / `ldrmodules` plugins:
- `ndlls` - loaded DLL count
- `avg_dlls_per_proc` - DLLs per process
- `not_in_load` - unlisted DLLs
- `not_in_init` - uninitialized DLLs
- `not_in_mem` - phantom DLLs
*DLL injection leaves traces in loader data structures.*
""")
with c2:
st.markdown("**Service Analysis (Most Important)**")
st.markdown("""
`svcscan` plugin:
- `nservices` - total service count
- `kernel_drivers` - kernel drivers
- `fs_drivers` - filesystem drivers
- `process_services` - process services
- `shared_process_services` - shared services
*Malware creates services for persistence - 1,550x difference in shared_process_services!*
""")
st.markdown("**Handle Analysis**")
st.markdown("""
`handles` plugin:
- `nhandles` - total handle count
- `nfile` - file handles
- `nevent` - event handles
- `nmutant` - mutex handles
- `ndesktop` - desktop handles
*Handle patterns reveal resource access behavior.*
""")
with c3:
st.markdown("**Memory Injection**")
st.markdown("""
`malfind` plugin:
- `ninjections` - detected injections
- `commitCharge` - committed memory
- `protection` - memory protections
*Direct detection of code injection - a key malware technique.*
""")
st.markdown("**Kernel Analysis**")
st.markdown("""
`callbacks` / `modules` plugins:
- `ncallbacks` - callback count
- `nanonymous` - anonymous callbacks
- `ngeneric` - generic callbacks
*Kernel callbacks are used for rootkit-like behavior.*
""")
st.divider()
# visualizations
st.subheader("Feature Analysis")
left, right = st.columns(2)
with left:
st.markdown("**Feature Correlation Heatmap**")
show_image("feature_correlation_heatmap.png")
st.caption("Correlation between top 30 selected features. High correlation (red) between ldrmodules features indicates redundancy.")
with right:
st.markdown("**PCA Projection**")
show_image("dataset_pca_projection.png")
st.caption("Left: 2D scatter plot of first two principal components. Right: Distribution along PC1 shows class separation - benign samples cluster together while malware spreads wider due to behavioral diversity across trojan/ransomware/spyware variants.")
# memory forensics patterns
st.divider()
st.subheader("Benign vs Malware Feature Comparison")
show_image("memory_forensics_patterns.png")
st.caption("Feature means by class across different Volatility plugin categories. Note the massive difference in Services features.")
# model comparison page
elif page == "Compare Models":
st.title("Model Comparison")
st.markdown("**Side-by-side performance analysis of all 5 models**")
st.divider()
# detailed comparison table
if any(results.values()):
rows = []
for key, data in results.items():
if data:
cm = data.get("confusion_matrix", [[0,0],[0,0]])
fp, fn = get_errors(cm)
tn, tp = cm[0][0], cm[1][1]
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
rows.append({
"Model": data.get("model", key),
"Test Accuracy": f"{data['test_accuracy']*100:.2f}%",
"CV Mean": f"{data['cv_mean']*100:.2f}%",
"CV Std": f"+/-{data['cv_std']*100:.3f}%",
"ROC AUC": f"{data.get('roc_auc', 0):.4f}",
"Precision": f"{precision:.4f}",
"Recall": f"{recall:.4f}",
"F1": f"{data.get('f1_score', 0):.4f}",
"FP": fp,
"FN": fn,
"Total Errors": fp + fn
})
st.dataframe(pd.DataFrame(rows), hide_index=True, use_container_width=True)
# accuracy bar chart using native streamlit
st.subheader("Accuracy Comparison")
chart_data = pd.DataFrame({
"Model": [r["Model"] for r in rows],
"Accuracy (%)": [float(r["Test Accuracy"].replace("%","")) for r in rows]
})
st.bar_chart(chart_data.set_index("Model"))
st.divider()
# model architecture breakdown
st.subheader("Model Architectures")
c1, c2 = st.columns(2)
with c1:
st.markdown("**Simple Models (Baselines)**")
st.markdown("""
**Linear Regression**
- Type: Regression adapted for classification
- Formula: `y = w1*x1 + w2*x2 + ... + b`
- Decision: `y > 0.5 -> Malware`
- Pros: Fast, interpretable weights
- Cons: Assumes linear relationship
- Result: 99.34% (77 errors)
""")
st.markdown("""
**Logistic Regression**
- Type: Probabilistic classifier
- Formula: `P(malware) = sigmoid(w*x + b)`
- Output: Probability 0-1
- Pros: Calibrated probabilities, interpretable coefficients
- Cons: May not converge on separable data
- Result: 99.47% (62 errors)
""")
st.markdown("""
**Naive Bayes**
- Type: Probabilistic (Bayes theorem)
- Assumption: Features are independent
- Variants: Gaussian (continuous), Bernoulli (binary)
- Pros: Very fast, works with small data
- Cons: Independence assumption rarely true
- Result: 99.16% (98 errors)
""")
with c2:
st.markdown("**Ensemble Models (Advanced)**")
st.markdown("""
**Random Forest**
- Type: Bagging ensemble
- Architecture: 100 decision trees
- Training: Bootstrap samples + random features
- Prediction: Majority vote
- Pros: Robust, handles non-linearity, feature importance
- Cons: Can overfit, black box
- Result: **100%** (0 errors) - BEST
""")
st.markdown("""
**XGBoost**
- Type: Gradient boosting ensemble
- Architecture: Sequential trees (200)
- Training: Each tree corrects previous errors
- Optimization: Gradient descent on loss
- Pros: Often state-of-the-art, GPU support
- Cons: Many hyperparameters, slower
- Result: **100%** (0 errors) - TIED BEST
""")
st.divider()
# key takeaways
st.subheader("Key Takeaways")
c1, c2, c3 = st.columns(3)
with c1:
st.success("""
**Best Models: Random Forest & XGBoost**
- 100% test accuracy (both)
- Zero classification errors
- Robust to overfitting (via ensemble)
- Built-in feature importance
- CV confirms: 99.99% generalization
""")
with c2:
st.info("""
**Most Stable: Linear Regression**
- Lowest CV variance (+/-0.06%)
- Simple and interpretable
- 99.34% proves linear separability
- Good baseline reference
""")
with c3:
st.warning("""
**Caution: Perfect Scores**
- 100% accuracy is suspicious
- Dataset may be "too easy"
- Strong feature separation (1,550x)
- Needs external validation
- May not generalize to new malware
""")
# linear regression page
elif page == "Linear Regression":
st.title("Linear Regression")
st.markdown("**Simple baseline - if a line can separate the classes, we don't need complexity**")
data = results.get("linear")
if data:
st.divider()
# metrics row
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Test Accuracy", f"{data['test_accuracy']*100:.2f}%")
c2.metric("CV Mean", f"{data['cv_mean']*100:.2f}%")
c3.metric("CV Std", f"+/-{data['cv_std']*100:.3f}%")
c4.metric("ROC AUC", f"{data['roc_auc']:.4f}")
fp, fn = get_errors(data['confusion_matrix'])
c5.metric("Total Errors", f"{fp + fn}")
st.divider()
left, right = st.columns([2, 1])
with left:
st.subheader("How It Works")
st.markdown("""
Linear regression finds the best-fit hyperplane through the feature space:
```
score = w1*feature1 + w2*feature2 + ... + wn*featuren + bias
```
For classification, we apply a threshold:
- If `score > 0.5` -> Malware
- If `score <= 0.5` -> Benign
**Why this matters:** The fact that a simple line achieves 99.34% accuracy
tells us the data is *nearly linearly separable*. The malware and benign
samples occupy distinct regions in feature space.
""")
st.subheader("Preprocessing Pipeline")
st.markdown("""
1. **RobustScaler** - Normalize features using median and IQR (resistant to outliers)
2. **SelectKBest(k=30)** - Chi-squared test selects top 30 most informative features
3. **Train/Test Split** - 80/20 stratified split preserves class balance
""")
with right:
st.subheader("Error Analysis")
cm = data['confusion_matrix']
st.markdown(f"""
| Metric | Value |
|--------|-------|
| True Negatives | {cm[0][0]:,} |
| False Positives | {cm[0][1]} |
| False Negatives | {cm[1][0]} |
| True Positives | {cm[1][1]:,} |
| **Total Errors** | **{fp + fn}** |
Errors are balanced (37 FP, 40 FN), meaning the model
isn't biased toward either class.
""")
st.divider()
# dashboard contains CV scores, ROC, confusion matrix, and metrics
st.subheader("Performance Dashboard")
show_image("linear_regression_dashboard.png")
st.caption("Cross-validation scores, ROC curve, confusion matrix, and metric bars in one view.")
# feature importance is unique, not in dashboard
st.subheader("Feature Importance (Coefficient Magnitude)")
show_image("linear_regression_feature_importance.png")
st.caption("Larger absolute coefficients = stronger influence on prediction")
else:
st.error("No results found - run the notebook first")
# logistic regression page
elif page == "Logistic Regression":
st.title("Logistic Regression")
st.markdown("**Probabilistic baseline - outputs calibrated confidence scores**")
data = results.get("logistic")
if data:
st.divider()
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Test Accuracy", f"{data['test_accuracy']*100:.2f}%")
c2.metric("CV Mean", f"{data['cv_mean']*100:.2f}%")
c3.metric("CV Std", f"+/-{data['cv_std']*100:.3f}%")
c4.metric("ROC AUC", f"{data['roc_auc']:.4f}")
fp, fn = get_errors(data['confusion_matrix'])
c5.metric("Total Errors", f"{fp + fn}")
st.divider()
left, right = st.columns([2, 1])
with left:
st.subheader("How It Works")
st.markdown("""
Logistic regression wraps linear regression in a sigmoid function:
```
z = w1*x1 + w2*x2 + ... + b
P(malware) = 1 / (1 + e^(-z))
```
This squishes output to [0, 1], giving us actual probabilities.
**Coefficient Interpretation:**
- Positive coefficient -> feature increases malware probability
- Negative coefficient -> feature decreases malware probability
- Larger magnitude -> stronger influence
**Example:** If `dlllist.avg_dlls_per_proc` has coefficient +2.5,
then more DLLs per process increases malware likelihood.
""")
with right:
st.subheader("Error Analysis")
cm = data['confusion_matrix']
st.markdown(f"""
| Metric | Value |
|--------|-------|
| True Negatives | {cm[0][0]:,} |
| False Positives | {cm[0][1]} |
| False Negatives | {cm[1][0]} |
| True Positives | {cm[1][1]:,} |
| **Total Errors** | **{fp + fn}** |
More FPs than FNs (41 vs 21) means
the model prioritizes catching malware
(99.64% recall) over avoiding false alarms.
""")
st.divider()
# dashboard contains CV scores, ROC, confusion matrix, and metrics
st.subheader("Performance Dashboard")
show_image("logistic_regression_dashboard.png")
st.caption("Cross-validation scores, ROC curve, confusion matrix, and metric bars in one view.")
# feature coefficients is unique
st.subheader("Feature Coefficients")
show_image("logistic_regression_feature_importance.png")
st.caption("Green = increases malware probability, Red = decreases malware probability")
else:
st.error("No results found - run the notebook first")
# naive bayes page
elif page == "Naive Bayes":
st.title("Naive Bayes")
st.markdown("**Fast probabilistic classifier using Bayes theorem**")
data = results.get("naive_bayes")
if data:
st.divider()
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Test Accuracy", f"{data.get('test_accuracy',0)*100:.2f}%")
c2.metric("CV Mean", f"{data.get('cv_mean',0)*100:.2f}%")
c3.metric("CV Std", f"+/-{data.get('cv_std',0)*100:.3f}%")
c4.metric("ROC AUC", f"{data.get('roc_auc',0):.4f}")
cm = data.get('confusion_matrix', [[0,0],[0,0]])
fp, fn = get_errors(cm)
c5.metric("Total Errors", f"{fp + fn}")
st.divider()
left, right = st.columns([2, 1])
with left:
st.subheader("How It Works")
st.markdown("""
Naive Bayes applies Bayes theorem with the "naive" assumption that
features are conditionally independent:
```
P(malware|features) = P(malware) * P(f1|malware) * P(f2|malware) * ...
```
**Two Variants Tested:**
| Variant | Assumption | Accuracy |
|---------|------------|----------|
| Gaussian NB | Features are normally distributed | 99.16% |
| Bernoulli NB | Features are binary (thresholded) | 99.44% |
**Why it works despite wrong assumption:**
The independence assumption is clearly violated (correlated features),
but Naive Bayes still performs well because the classes are so well-separated.
""")
with right:
st.subheader("Error Analysis")
st.markdown(f"""
| Metric | Value |
|--------|-------|
| True Negatives | {cm[0][0]:,} |
| False Positives | {cm[0][1]} |
| False Negatives | {cm[1][0]} |
| True Positives | {cm[1][1]:,} |
| **Total Errors** | **{fp + fn}** |
More FPs than FNs means the model
errs on the side of caution -
better to flag benign as malware
than miss real threats.
""")
st.divider()
# dashboard has CV, confusion, ROC, metrics
st.subheader("Performance Dashboard")
show_image("naive_bayes_dashboard.png")
st.caption("Cross-validation scores, confusion matrix, ROC curve, and metric bars.")
# gaussian vs bernoulli comparison is unique
st.subheader("Gaussian vs Bernoulli Comparison")
show_image("naive_bayes_cv_comparison.png")
st.caption("Bernoulli NB slightly outperforms Gaussian NB on this dataset.")
else:
st.error("No results found - run the notebook first")
# random forest page
elif page == "Random Forest":
st.title("Random Forest")
st.markdown("**Ensemble of decision trees - THE BEST PERFORMER**")
data = results.get("random_forest")
if data:
st.success("BEST MODEL - 100% test accuracy with zero classification errors!")
st.divider()
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Test Accuracy", "100.00%", delta="Best")
c2.metric("CV Mean", f"{data['cv_mean']*100:.2f}%")
c3.metric("CV Std", f"+/-{data['cv_std']*100:.3f}%")
c4.metric("ROC AUC", f"{data['roc_auc']:.4f}")
c5.metric("Total Errors", "0", delta="Perfect")
st.divider()
left, right = st.columns([2, 1])
with left:
st.subheader("How It Works")
st.markdown("""
Random Forest builds an ensemble of decision trees using **bagging**:
1. Create 100 decision trees
2. Each tree trains on a random bootstrap sample (with replacement)
3. At each split, consider only a random subset of features
4. Final prediction = majority vote across all trees
**Why it works so well:**
- Individual trees may overfit, but averaging cancels out noise
- Random feature selection creates diverse trees
- Bagging reduces variance without increasing bias
**Our Configuration:**
| Parameter | Value |
|-----------|-------|
| n_estimators | 100 trees |
| max_depth | 20 levels |
| random_state | 42 (reproducible) |
""")
with right:
st.subheader("Perfect Classification")
cm = data['confusion_matrix']
st.markdown(f"""
| Metric | Value |
|--------|-------|
| True Negatives | {cm[0][0]:,} |
| False Positives | {cm[0][1]} |
| False Negatives | {cm[1][0]} |
| True Positives | {cm[1][1]:,} |
| **Total Errors** | **0** |
Perfect diagonal confusion matrix -
every single sample classified correctly.
""")
st.warning("""
**Caution:** 100% accuracy is unusual and
may indicate the dataset is "too easy"
or the model has memorized patterns that
won't generalize to new malware.
""")
st.divider()
# dashboard has CV, confusion, ROC, metrics
st.subheader("Performance Dashboard")
show_image("random_forest_dashboard.png")
st.caption("Cross-validation scores, confusion matrix, ROC curve, and metric bars.")
# feature importance is unique
st.subheader("Feature Importance (Gini Impurity)")
show_image("random_forest_feature_importance.png")
st.info("""
**Top 5 Most Important Features:**
1. `svcscan.shared_process_services` (18.2%) - Services in shared processes
2. `svcscan.nservices` (13.7%) - Total service count
3. `svcscan.kernel_drivers` (10.0%) - Kernel driver registrations
4. `handles.nevent` (5.3%) - Event handle count
5. `pslist.nprocs64bit` (4.8%) - 64-bit process count
**Service manipulation is the #1 indicator of malware!**
""")
# decision tree visualization
st.divider()
st.subheader("Decision Tree Visualization")
show_image("random_forest_tree.png")
st.caption("""
Sample decision tree from the Random Forest ensemble (depth limited to 3 for readability).
Each node shows the feature being split and the threshold value. Orange nodes indicate
malware-leaning decisions, blue nodes indicate benign-leaning decisions. The tree demonstrates
how service manipulation features (like shared_process_services) dominate early splits.
""")
else:
st.error("No results found - run the notebook first")
# xgboost page
elif page == "XGBoost":
st.title("XGBoost")
st.markdown("**Gradient boosting - sequential error correction**")
data = results.get("xgboost")
if data:
st.divider()
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Test Accuracy", f"{data['test_accuracy']*100:.2f}%")
c2.metric("CV Mean", f"{data['cv_mean']*100:.2f}%")
c3.metric("CV Std", f"+/-{data['cv_std']*100:.3f}%")
c4.metric("ROC AUC", f"{data['roc_auc']:.4f}")
fp, fn = get_errors(data['confusion_matrix'])
c5.metric("Total Errors", f"{fp + fn}")
st.divider()
left, right = st.columns([2, 1])
with left:
st.subheader("How It Works")
st.markdown("""
Unlike Random Forest (parallel trees), XGBoost builds trees **sequentially**:
1. Train tree 1 on the data
2. Calculate residual errors
3. Train tree 2 to predict those errors
4. Add tree 2's predictions to tree 1's
5. Repeat for N iterations
**Gradient Boosting:** Uses gradient descent to minimize loss function.
Each new tree is trained to correct the mistakes of the ensemble so far.
**Advantages over Random Forest:**
- Often achieves higher accuracy
- GPU acceleration support
- Built-in regularization
- Handles missing values
""")
with right:
st.subheader("Best Hyperparameters")
if "best_params" in data:
params = data["best_params"]
st.markdown(f"""
| Parameter | Value |
|-----------|-------|
| n_estimators | {params.get('n_estimators', '?')} |
| max_depth | {params.get('max_depth', '?')} |
| learning_rate | {params.get('learning_rate', '?')} |
| subsample | {params.get('subsample', '?')} |
| colsample_bytree | {params.get('colsample_bytree', '?')} |
| min_child_weight | {params.get('min_child_weight', '?')} |
| gamma | {params.get('gamma', '?')} |
Found via RandomizedSearchCV
(20 iterations, 3-fold CV)
""")
st.divider()
# dashboard has CV, confusion, ROC, metrics
st.subheader("Performance Dashboard")
show_image("xgboost_dashboard.png")
st.caption("Cross-validation scores, confusion matrix, ROC curve, and metric bars.")
# feature importance is unique
st.subheader("Feature Importance (Gain)")
show_image("xgboost_feature_importance_curves.png")
# top features table
if "top_features" in data:
st.subheader("Top 10 Features by Information Gain")
feat_df = pd.DataFrame(data["top_features"])
feat_df["importance"] = feat_df["importance"].round(1)
feat_df.columns = ["Feature", "Gain Score"]
st.dataframe(feat_df, hide_index=True, use_container_width=True)
# decision tree visualization
st.divider()
st.subheader("Boosted Tree Visualization")
show_image("xgboost_tree.png")
st.caption("""
First boosted tree from the XGBoost ensemble (max_depth=3). Unlike Random Forest where trees
vote independently, XGBoost trees are built sequentially - each tree corrects errors from
previous trees. Leaf values represent the prediction contribution from this tree, which are
summed across all 200 trees to produce the final prediction. Green leaves indicate benign
predictions, pink leaves indicate malware predictions.
""")
else:
st.error("No results found - run the notebook first")
# hardware page
elif page == "Hardware":
st.title("Hardware Testing")
st.markdown("**CPU vs GPU performance benchmarking for XGBoost**")
st.divider()
st.markdown("""
XGBoost supports GPU acceleration via CUDA. We benchmarked training performance
to determine when GPU acceleration is beneficial.
""")
# show both charts side by side
c1, c2 = st.columns(2)
with c1:
st.subheader("Training Time Comparison")
show_image("hardware_cpu_vs_gpu_performance.png")
with c2:
st.subheader("Resource Utilization")
show_image("hardware_utilization.png")
st.divider()
st.subheader("Benchmark Results")
c1, c2, c3 = st.columns(3)
with c1:
st.markdown("""
**CPU Performance**
- Training time: 2-5 seconds
- Full CPU utilization
- No special hardware needed
- Sufficient for this dataset size
""")
with c2:
st.markdown("""
**GPU Performance**
- Training time: 1-2 seconds
- Speedup: ~2-3x faster
- Requires CUDA-compatible GPU
- Benefits increase with data size
""")
with c3:
st.markdown("""
**Recommendation**
- For 58k samples: CPU is fine
- For 1M+ samples: GPU recommended
- For hyperparameter search: GPU saves hours
- For inference: CPU is fast enough
""")