This repository was archived by the owner on May 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalware_classification.py
More file actions
2010 lines (1677 loc) · 80.8 KB
/
Copy pathmalware_classification.py
File metadata and controls
2010 lines (1677 loc) · 80.8 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
"""
Malware Classification using Hyperopt (Bayesian Optimization via TPE).
Enhanced version with comprehensive reporting and visualization.
Supports two classification modes:
- maliciousness: Binary classification (benign=0 vs malicious=1)
- family: Multi-class classification by malware family
Features:
- Multiple ML models with hyperparameter tuning (including ResNet-18)
- Stratified cross-validation
- Optional grouped CV by family (for maliciousness mode)
- Sample weighting for imbalanced classes
- Comprehensive reporting with plots and saved results
"""
import numpy as np
import warnings
import os
import json
from datetime import datetime
# Am Anfang des Skripts, VOR jedem TensorFlow-Import:
import multiprocessing
multiprocessing.set_start_method('spawn', force=True)
from matplotlib import pyplot as plt
from sklearn.decomposition import PCA
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings('ignore')
os.environ["PYTHONWARNINGS"] = "ignore"
from typing import Dict, List, Tuple, Any, Optional, Literal, Set
import weaviate
from sklearn.model_selection import (
cross_val_score, StratifiedKFold, StratifiedGroupKFold, train_test_split, GroupShuffleSplit
)
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.dummy import DummyClassifier
from sklearn.metrics import (
classification_report, confusion_matrix, ConfusionMatrixDisplay,
f1_score, precision_score, recall_score, accuracy_score
)
from sklearn.base import BaseEstimator, ClassifierMixin
import joblib
import xgboost as xgb
import lightgbm as lgb
# Hyperopt
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials, space_eval
import pandas as pd
WEAVIATE_HOST = "weaviate.malwareuniverse.org"
WEAVIATE_HTTP_PORT = 443
WEAVIATE_GRPC_PORT = 50051
COLLECTION_NAME = "pre_traind_distilberd3_3"
SPLIT_KEY_SHA_FIELDS = ("sha256_hash", "sha256", "sha256sum", "shasum")
# Valid classification modes
ClassificationMode = Literal["maliciousness", "malware_family", "threat_actor"]
def _extract_split_key(properties: Dict[str, Any], fallback_id: str) -> str:
for field_name in SPLIT_KEY_SHA_FIELDS:
value = properties.get(field_name)
if value not in (None, ""):
return str(value).strip().lower()
sample_key = properties.get("sample_id") or properties.get("id")
if sample_key not in (None, ""):
return str(sample_key).strip()
return str(fallback_id).strip()
def _normalize_split_keys(split_keys: List[str]) -> np.ndarray:
return np.array([str(key).strip().lower() for key in split_keys], dtype=object)
def _build_holdout_indices(
y: np.ndarray,
split_keys: List[str],
holdout_size: float,
cv_groups: Optional[np.ndarray],
fixed_holdout_keys: Optional[Set[str]] = None,
random_state: int = 42,
) -> Tuple[np.ndarray, np.ndarray, str, Set[str]]:
normalized_split_keys = _normalize_split_keys(split_keys)
unique_split_key_count = len(set(normalized_split_keys.tolist()))
duplicate_split_key_count = len(normalized_split_keys) - unique_split_key_count
if duplicate_split_key_count > 0:
print(
f" Warning: found {duplicate_split_key_count} duplicate split keys. "
"Cross-collection holdout identity can differ for tied keys."
)
if fixed_holdout_keys is not None:
normalized_target_keys = {str(key).strip().lower() for key in fixed_holdout_keys}
available_keys = set(normalized_split_keys.tolist())
missing_target_keys = normalized_target_keys - available_keys
if missing_target_keys:
raise ValueError(
f"Collection is missing {len(missing_target_keys)} required holdout keys. "
"Cannot enforce identical holdout split."
)
holdout_mask = np.array([key in normalized_target_keys for key in normalized_split_keys], dtype=bool)
holdout_idx = np.where(holdout_mask)[0]
train_idx = np.where(~holdout_mask)[0]
if len(train_idx) == 0 or len(holdout_idx) == 0:
raise ValueError("Invalid fixed holdout split: empty train or holdout partition.")
split_strategy = f"Fixed holdout by split key ({len(normalized_target_keys)} keys)"
holdout_key_set = set(normalized_split_keys[holdout_idx].tolist())
return train_idx, holdout_idx, split_strategy, holdout_key_set
stable_order = np.argsort(normalized_split_keys, kind="mergesort")
ordered_indices = np.arange(len(y))[stable_order]
y_ordered = y[stable_order]
cv_groups_ordered = cv_groups[stable_order] if cv_groups is not None else None
if cv_groups_ordered is not None:
splitter = GroupShuffleSplit(n_splits=1, test_size=holdout_size, random_state=random_state)
train_pos, holdout_pos = next(
splitter.split(np.arange(len(y_ordered)), y_ordered, groups=cv_groups_ordered)
)
split_strategy = "GroupShuffleSplit on stable split_key order"
else:
try:
train_pos, holdout_pos = train_test_split(
np.arange(len(y_ordered)),
test_size=holdout_size,
random_state=random_state,
stratify=y_ordered
)
split_strategy = "Stratified train_test_split on stable split_key order"
except ValueError:
train_pos, holdout_pos = train_test_split(
np.arange(len(y_ordered)),
test_size=holdout_size,
random_state=random_state
)
split_strategy = "Unstratified train_test_split on stable split_key order"
train_idx = ordered_indices[train_pos]
holdout_idx = ordered_indices[holdout_pos]
holdout_key_set = set(normalized_split_keys[holdout_idx].tolist())
return train_idx, holdout_idx, split_strategy, holdout_key_set
def _filter_dataset_by_keys(
X: np.ndarray,
y: np.ndarray,
split_keys: List[str],
groups: Optional[np.ndarray],
allowed_keys: Set[str],
) -> Tuple[np.ndarray, np.ndarray, List[str], Optional[np.ndarray], int]:
normalized_split_keys = _normalize_split_keys(split_keys)
keep_mask = np.array([key in allowed_keys for key in normalized_split_keys], dtype=bool)
dropped_count = int((~keep_mask).sum())
if dropped_count == 0:
return X, y, split_keys, groups, dropped_count
X_filtered = X[keep_mask]
y_filtered = y[keep_mask]
groups_filtered = groups[keep_mask] if groups is not None else None
split_keys_filtered = [key for key, keep in zip(split_keys, keep_mask) if keep]
return X_filtered, y_filtered, split_keys_filtered, groups_filtered, dropped_count
def _scalar_holdout_metrics(metrics: Dict[str, Any]) -> Dict[str, float]:
report = metrics.get("classification_report", {})
macro_avg = report.get("macro avg", {}) if isinstance(report, dict) else {}
weighted_avg = report.get("weighted avg", {}) if isinstance(report, dict) else {}
return {
"accuracy": float(metrics["accuracy"]),
"f1_weighted": float(metrics["f1_weighted"]),
"f1_macro": float(metrics["f1_macro"]),
"precision_macro": float(macro_avg.get("precision", 0.0)),
"recall_macro": float(macro_avg.get("recall", 0.0)),
"precision_weighted": float(metrics["precision_weighted"]),
"recall_weighted": float(metrics["recall_weighted"]),
}
def _build_holdout_details_payload(
tuner: Any,
metrics: Dict[str, Any],
split_strategy: str,
holdout_size: float,
holdout_key_set: Set[str],
) -> Dict[str, Any]:
report = metrics.get("classification_report", {})
y_true = np.asarray(metrics.get("y_true", []))
y_pred = np.asarray(metrics.get("y_pred", []))
true_labels, true_counts = np.unique(y_true, return_counts=True) if y_true.size else ([], [])
pred_labels, pred_counts = np.unique(y_pred, return_counts=True) if y_pred.size else ([], [])
def _label_name(raw_label: Any) -> str:
try:
return str(tuner.classes_[int(raw_label)])
except Exception:
return str(raw_label)
true_distribution = [
{
"label_encoded": int(label),
"label_name": _label_name(label),
"count": int(count),
}
for label, count in zip(true_labels, true_counts)
]
predicted_distribution = [
{
"label_encoded": int(label),
"label_name": _label_name(label),
"count": int(count),
}
for label, count in zip(pred_labels, pred_counts)
]
return {
"best_model_name": tuner.best_model_name,
"best_model_cv_score": float(tuner.results[tuner.best_model_name]["cv_score_mean"]),
"best_model_cv_std": float(tuner.results[tuner.best_model_name]["cv_score_std"]),
"best_model_params": tuner.best_params,
"split_strategy": split_strategy,
"requested_holdout_size": float(holdout_size),
"holdout_split_key_count": int(len(holdout_key_set)),
"holdout_sample_count": int(y_true.size),
"overall_metrics": _scalar_holdout_metrics(metrics),
"classification_report": report,
"macro_avg": report.get("macro avg", {}) if isinstance(report, dict) else {},
"weighted_avg": report.get("weighted avg", {}) if isinstance(report, dict) else {},
"confusion_matrix": metrics.get("confusion_matrix"),
"true_label_distribution": true_distribution,
"predicted_label_distribution": predicted_distribution,
}
class ResultsManager:
"""Manages saving and organizing all experiment results."""
def __init__(self, output_dir: str = "results"):
self.output_dir = output_dir
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.run_dir = os.path.join(output_dir, f"run_{self.timestamp}")
self.plots_dir = os.path.join(self.run_dir, "plots")
self.models_dir = os.path.join(self.run_dir, "models")
self.reports_dir = os.path.join(self.run_dir, "reports")
# Create directories
for d in [self.run_dir, self.plots_dir, self.models_dir, self.reports_dir]:
os.makedirs(d, exist_ok=True)
print(f"✓ Results will be saved to: {self.run_dir}")
def save_figure(self, fig, name: str, dpi: int = 150):
"""Save a matplotlib figure."""
filepath = os.path.join(self.plots_dir, f"{name}.png")
fig.savefig(filepath, dpi=dpi, bbox_inches='tight', facecolor='white', edgecolor='none')
plt.close(fig)
print(f" ✓ Saved: {filepath}")
return filepath
def save_json(self, data: Dict, name: str):
"""Save data as JSON."""
filepath = os.path.join(self.reports_dir, f"{name}.json")
# Convert numpy types to Python types
def convert(obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, (np.int64, np.int32)):
return int(obj)
elif isinstance(obj, (np.float64, np.float32)):
return float(obj)
elif isinstance(obj, dict):
return {k: convert(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert(v) for v in obj]
return obj
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(convert(data), f, indent=2)
print(f" ✓ Saved: {filepath}")
return filepath
def save_csv(self, df: pd.DataFrame, name: str):
"""Save DataFrame as CSV."""
filepath = os.path.join(self.reports_dir, f"{name}.csv")
df.to_csv(filepath, index=True)
print(f" ✓ Saved: {filepath}")
return filepath
def save_text(self, text: str, name: str):
"""Save text content."""
filepath = os.path.join(self.reports_dir, f"{name}.txt")
with open(filepath, 'w', encoding='utf-8') as f:
f.write(text)
print(f" ✓ Saved: {filepath}")
return filepath
def save_model(self, model, name: str):
"""Save a model using joblib."""
filepath = os.path.join(self.models_dir, f"{name}.joblib")
joblib.dump(model, filepath)
print(f" ✓ Saved: {filepath}")
return filepath
class ResNet18Classifier(BaseEstimator, ClassifierMixin):
"""1D ResNet-18 Classifier for embedding vectors."""
def __init__(
self,
base_filters: int = 64,
kernel_size: int = 3,
dropout_rate: float = 0.3,
learning_rate: float = 0.001,
batch_size: int = 32,
epochs: int = 100,
use_dropout: bool = True,
random_state: int = 42,
):
self.base_filters = base_filters
self.kernel_size = kernel_size
self.dropout_rate = dropout_rate
self.learning_rate = learning_rate
self.batch_size = batch_size
self.epochs = epochs
self.use_dropout = bool(use_dropout)
self.random_state = random_state
self.model_ = None
self.classes_ = None
self.n_classes_ = None
self.input_dim_ = None
self.history_ = None
def _residual_block(self, x, filters, kernel_size, downsample=False):
from keras import layers, Model
stride = 2 if downsample else 1
shortcut = x
x = layers.Conv1D(filters=filters, kernel_size=kernel_size, strides=stride, padding='same', use_bias=False)(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.Conv1D(filters=filters, kernel_size=kernel_size, strides=1, padding='same', use_bias=False)(x)
x = layers.BatchNormalization()(x)
if downsample or shortcut.shape[-1] != filters:
shortcut = layers.Conv1D(filters=filters, kernel_size=1, strides=stride, padding='same', use_bias=False)(
shortcut)
shortcut = layers.BatchNormalization()(shortcut)
x = layers.Add()([x, shortcut])
x = layers.Activation('relu')(x)
return x
def _build_model(self):
import tensorflow as tf
from tensorflow import keras
from keras import layers, Model
tf.random.set_seed(self.random_state)
inputs = layers.Input(shape=(self.input_dim_, 1))
x = layers.Conv1D(filters=self.base_filters, kernel_size=7, strides=2, padding='same', use_bias=False)(inputs)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.MaxPooling1D(pool_size=3, strides=2, padding='same')(x)
# Stage 1
x = self._residual_block(x, self.base_filters, self.kernel_size, downsample=False)
x = self._residual_block(x, self.base_filters, self.kernel_size, downsample=False)
if self.use_dropout:
x = layers.Dropout(self.dropout_rate)(x)
# Stage 2
x = self._residual_block(x, self.base_filters * 2, self.kernel_size, downsample=True)
x = self._residual_block(x, self.base_filters * 2, self.kernel_size, downsample=False)
if self.use_dropout:
x = layers.Dropout(self.dropout_rate)(x)
# Stage 3
x = self._residual_block(x, self.base_filters * 4, self.kernel_size, downsample=True)
x = self._residual_block(x, self.base_filters * 4, self.kernel_size, downsample=False)
if self.use_dropout:
x = layers.Dropout(self.dropout_rate)(x)
# Stage 4
x = self._residual_block(x, self.base_filters * 8, self.kernel_size, downsample=True)
x = self._residual_block(x, self.base_filters * 8, self.kernel_size, downsample=False)
if self.use_dropout:
x = layers.Dropout(self.dropout_rate)(x)
x = layers.GlobalAveragePooling1D()(x)
if self.n_classes_ == 2:
outputs = layers.Dense(1, activation='sigmoid')(x)
else:
outputs = layers.Dense(self.n_classes_, activation='softmax')(x)
model = Model(inputs, outputs)
optimizer = keras.optimizers.Adam(learning_rate=self.learning_rate)
if self.n_classes_ == 2:
model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
else:
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
def fit(self, X, y, sample_weight=None):
from tensorflow import keras
from keras.callbacks import EarlyStopping
self.classes_ = np.unique(y)
self.n_classes_ = len(self.classes_)
self.input_dim_ = X.shape[1]
X_reshaped = X.reshape(X.shape[0], X.shape[1], 1)
self.model_ = self._build_model()
callbacks = [
EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True, verbose=0),
keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=1e-6, verbose=0)
]
if self.n_classes_ == 2:
y_train = y.astype(np.float32)
else:
y_train = y.astype(np.int32)
self.history_ = self.model_.fit(
X_reshaped, y_train,
batch_size=self.batch_size,
epochs=self.epochs,
validation_split=0.15,
callbacks=callbacks,
sample_weight=sample_weight,
verbose=0
)
return self
def predict(self, X):
if self.model_ is None:
raise ValueError("Model not fitted yet.")
X_reshaped = X.reshape(X.shape[0], X.shape[1], 1)
if self.n_classes_ == 2:
proba = self.model_.predict(X_reshaped, verbose=0)
return (proba.flatten() > 0.5).astype(int)
else:
proba = self.model_.predict(X_reshaped, verbose=0)
return np.argmax(proba, axis=1)
def predict_proba(self, X):
if self.model_ is None:
raise ValueError("Model not fitted yet.")
X_reshaped = X.reshape(X.shape[0], X.shape[1], 1)
proba = self.model_.predict(X_reshaped, verbose=0)
if self.n_classes_ == 2:
proba = proba.flatten()
return np.column_stack([1 - proba, proba])
else:
return proba
def get_params(self, deep=True):
return {
'base_filters': self.base_filters,
'kernel_size': self.kernel_size,
'dropout_rate': self.dropout_rate,
'learning_rate': self.learning_rate,
'batch_size': self.batch_size,
'epochs': self.epochs,
'use_dropout': self.use_dropout,
'random_state': self.random_state,
}
def set_params(self, **params):
for key, value in params.items():
setattr(self, key, value)
return self
class MalwareDataLoader:
"""Loads malware embeddings and labels from Weaviate."""
def __init__(
self,
host: str = WEAVIATE_HOST,
http_port: int = WEAVIATE_HTTP_PORT,
grpc_port: int = WEAVIATE_GRPC_PORT,
collection_name: str = COLLECTION_NAME
):
self.host = host
self.http_port = http_port
self.grpc_port = grpc_port
self.collection_name = collection_name
self.weaviate_client = None
def _connect_weaviate(self):
self.weaviate_client = weaviate.connect_to_custom(
http_host=self.host,
http_port=self.http_port,
http_secure=True,
grpc_host=self.host,
grpc_port=self.grpc_port,
grpc_secure=False,
)
def _close_weaviate(self):
if self.weaviate_client:
self.weaviate_client.close()
def load_dataset(
self,
mode: ClassificationMode = "maliciousness",
min_family_samples: int = 5,
) -> Tuple[np.ndarray, np.ndarray, List[str], Optional[np.ndarray], Dict[str, Any]]:
print(f"\n{'=' * 50}")
print(f"Loading malware dataset")
print(f" Mode: {mode}")
print(f" Collection: {self.collection_name}")
print(f"{'=' * 50}")
self._connect_weaviate()
try:
collection = self.weaviate_client.collections.get(self.collection_name)
embeddings = []
labels = []
split_keys = []
families = []
is_malicious_list = []
cursor = None
batch_size = 100
while True:
try:
if cursor is None:
response = collection.query.fetch_objects(limit=batch_size, include_vector=True)
else:
response = collection.query.fetch_objects(limit=batch_size, include_vector=True, after=cursor)
except Exception as e:
print(f" Warning: Query failed, trying alternative method...")
raise e
if not response.objects:
break
for obj in response.objects:
properties = obj.properties or {}
sample_id = properties.get("sample_id") or properties.get("id") or str(obj.uuid)
split_key = _extract_split_key(properties, fallback_id=sample_id)
family = properties.get("malware_family", "unknown")
vec = None
if obj.vector:
if isinstance(obj.vector, dict):
vec = obj.vector.get("default") or list(obj.vector.values())[0]
else:
vec = obj.vector
if vec is None:
continue
embeddings.append(np.array(vec))
families.append(str(family) if family else "unknown")
split_keys.append(split_key)
cursor = response.objects[-1].uuid
print(f" Loaded {len(embeddings)} samples...", end='\r')
if len(response.objects) < batch_size:
break
print(f"\n✓ Loaded {len(embeddings)} samples from Weaviate")
X = np.array(embeddings)
families_arr = np.array(families)
family_encoder = LabelEncoder()
family_groups = family_encoder.fit_transform(families_arr)
if mode == "maliciousness":
y = is_malicious_arr
groups = family_groups
label_names = {0: "benign", 1: "malicious"}
unique, counts = np.unique(y, return_counts=True)
info = {
"mode": mode,
"embedding_dim": X.shape[1],
"n_samples": len(y),
"n_classes": 2,
"label_names": label_names,
"class_distribution": dict(zip(unique.tolist(), counts.tolist())),
"n_families": len(family_encoder.classes_),
"family_encoder": family_encoder,
}
print(f"\n Binary classification (maliciousness)")
print(f" Embedding dimension: {X.shape[1]}")
for cls, cnt in zip(unique, counts):
print(f" {label_names[cls]}: {cnt} samples ({cnt / len(y) * 100:.1f}%)")
print(f" Families for grouping: {len(family_encoder.classes_)} unique")
else: # family mode
unique_families, family_counts = np.unique(families_arr, return_counts=True)
valid_families = unique_families[family_counts >= min_family_samples]
if len(valid_families) < 2:
raise ValueError(
f"Not enough families with >= {min_family_samples} samples. "
f"Found: {len(valid_families)}. Try lowering min_family_samples."
)
valid_mask = np.isin(families_arr, valid_families)
X = X[valid_mask]
families_filtered = families_arr[valid_mask]
split_keys = [key for key, m in zip(split_keys, valid_mask) if m]
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(families_filtered)
groups = None
label_names = {i: name for i, name in enumerate(label_encoder.classes_)}
unique, counts = np.unique(y, return_counts=True)
info = {
"mode": mode,
"embedding_dim": X.shape[1],
"n_samples": len(y),
"n_classes": len(label_encoder.classes_),
"label_names": label_names,
"label_encoder": label_encoder,
"class_distribution": dict(zip(unique.tolist(), counts.tolist())),
"dropped_families": len(unique_families) - len(valid_families),
"min_family_samples": min_family_samples,
}
print(f"\n Multi-class classification (family)")
print(f" Embedding dimension: {X.shape[1]}")
print(f" Classes: {len(label_encoder.classes_)} families")
print(
f" Dropped {len(unique_families) - len(valid_families)} families with < {min_family_samples} samples")
print(f" Class distribution (top 10):")
sorted_indices = np.argsort(counts)[::-1][:10]
for idx in sorted_indices:
cls = unique[idx]
cnt = counts[idx]
print(f" {label_names[cls]}: {cnt} samples ({cnt / len(y) * 100:.1f}%)")
if len(unique) > 10:
print(f" ... and {len(unique) - 10} more families")
return X, y, split_keys, groups, info
finally:
self._close_weaviate()
@staticmethod
def get_sample_weights(y: np.ndarray, strategy: str = "balanced") -> np.ndarray:
unique, counts = np.unique(y, return_counts=True)
n_samples = len(y)
if strategy == "balanced":
class_weights = {cls: n_samples / (len(unique) * cnt) for cls, cnt in zip(unique, counts)}
elif strategy == "sqrt_balanced":
class_weights = {cls: np.sqrt(n_samples / (len(unique) * cnt)) for cls, cnt in zip(unique, counts)}
else:
return np.ones(len(y))
weights = np.array([class_weights[label] for label in y])
return weights
class MalwareHyperoptTuner:
"""Hyperparameter tuning using Hyperopt for malware classification."""
def __init__(
self,
random_state: int = 42,
scoring: str = "f1_weighted"
):
self.random_state = random_state
self.scoring = scoring
self.best_model = None
self.best_params = None
self.best_model_name = None
self.results = {}
self.label_encoder = LabelEncoder()
self.classes_ = None
self.info = None
self.results_manager = None
def get_hyperopt_spaces(self) -> Dict[str, Dict[str, Any]]:
"""Define Hyperopt search spaces for classification models."""
spaces = {
"resnet18": {
"model_class": ResNet18Classifier,
"static_params": {"random_state": self.random_state, "epochs": 100, "n_jobs": 1},
"space": {
"base_filters": hp.choice("resnet_base_filters", [32, 64, 128]),
"kernel_size": hp.choice("resnet_kernel_size", [3, 5, 7]),
"dropout_rate": hp.uniform("resnet_dropout_rate", 0.1, 0.5),
"learning_rate": hp.loguniform("resnet_learning_rate", np.log(1e-5), np.log(1e-2)),
"batch_size": hp.choice("resnet_batch_size", [16, 32, 64, 128]),
"use_dropout": hp.randint("resnet_use_dropout", 2),
},
"supports_sample_weight": True,
"skip_pca": True,
},
"xgboost": {
"model_class": xgb.XGBClassifier,
"static_params": {"random_state": self.random_state, "verbosity": 0, "use_label_encoder": False,
"eval_metric": "mlogloss", "device": "cpu"},
"space": {
"n_estimators": hp.choice("xgb_n_estimators", [50, 100, 200, 300, 500, 750, 1000]),
"max_depth": hp.choice("xgb_max_depth", [3, 4, 5, 6, 7, 8, 10, 12, 15]),
"learning_rate": hp.loguniform("xgb_learning_rate", np.log(0.005), np.log(0.3)),
"subsample": hp.uniform("xgb_subsample", 0.5, 1.0),
"colsample_bytree": hp.uniform("xgb_colsample_bytree", 0.5, 1.0),
"min_child_weight": hp.choice("xgb_min_child_weight", [1, 3, 5, 7, 10]),
"gamma": hp.uniform("xgb_gamma", 0, 0.5),
"reg_alpha": hp.loguniform("xgb_reg_alpha", np.log(1e-6), np.log(10.0)),
"reg_lambda": hp.loguniform("xgb_reg_lambda", np.log(1e-3), np.log(100.0)),
},
"supports_sample_weight": True
},
"lightgbm": {
"model_class": lgb.LGBMClassifier,
"static_params": {"random_state": self.random_state, "verbosity": -1, "device": "cpu"},
"space": {
"n_estimators": hp.choice("lgb_n_estimators", [50, 100, 200, 300, 500, 750, 1000]),
"max_depth": hp.choice("lgb_max_depth", [-1, 3, 5, 7, 10, 15, 20]),
"learning_rate": hp.loguniform("lgb_learning_rate", np.log(0.005), np.log(0.3)),
"num_leaves": hp.choice("lgb_num_leaves", [15, 31, 63, 127, 255]),
"subsample": hp.uniform("lgb_subsample", 0.5, 1.0),
"colsample_bytree": hp.uniform("lgb_colsample_bytree", 0.5, 1.0),
"min_child_samples": hp.choice("lgb_min_child_samples", [5, 10, 20, 50, 100]),
"reg_alpha": hp.loguniform("lgb_reg_alpha", np.log(1e-6), np.log(10.0)),
"reg_lambda": hp.loguniform("lgb_reg_lambda", np.log(1e-6), np.log(10.0)),
"class_weight": hp.choice("lgb_class_weight", [None, "balanced"]),
},
"supports_sample_weight": True
},
"random_forest": {
"model_class": RandomForestClassifier,
"static_params": {"random_state": self.random_state, "n_jobs": -1},
"space": {
"n_estimators": hp.choice("rf_n_estimators", [50, 100, 200, 300, 500, 750]),
"max_depth": hp.choice("rf_max_depth", [None, 10, 20, 30, 50, 100]),
"min_samples_split": hp.choice("rf_min_samples_split", [2, 5, 10, 20]),
"min_samples_leaf": hp.choice("rf_min_samples_leaf", [1, 2, 4, 8]),
"max_features": hp.choice("rf_max_features", ["sqrt", "log2", 0.3, 0.5, 0.7]),
"class_weight": hp.choice("rf_class_weight", [None, "balanced", "balanced_subsample"]),
},
"supports_sample_weight": True
},
"svc": {
"model_class": SVC,
"static_params": {"random_state": self.random_state, "probability": True},
"space": {
"C": hp.loguniform("svc_C", np.log(0.01), np.log(1000)),
"kernel": hp.choice("svc_kernel", ["rbf", "linear", "poly"]),
"gamma": hp.choice("svc_gamma", ["scale", "auto", 0.001, 0.01, 0.1]),
"degree": hp.choice("svc_degree", [2, 3, 4]),
"class_weight": hp.choice("svc_class_weight", [None, "balanced"]),
},
"supports_sample_weight": True
},
"logistic_regression": {
"model_class": LogisticRegression,
"static_params": {"random_state": self.random_state, "max_iter": 2000, "n_jobs": -1},
"space": {
"C": hp.loguniform("lr_C", np.log(1e-4), np.log(100)),
"solver": hp.choice("lr_solver", ["lbfgs", "saga"]),
"class_weight": hp.choice("lr_class_weight", [None, "balanced"]),
"penalty": hp.choice("lr_penalty", ["l2", None]),
},
"supports_sample_weight": True
},
"knn": {
"model_class": KNeighborsClassifier,
"static_params": {"n_jobs": -1},
"space": {
"n_neighbors": hp.choice("knn_n_neighbors", [1, 3, 5, 7, 11, 15, 21, 31]),
"weights": hp.choice("knn_weights", ["uniform", "distance"]),
"metric": hp.choice("knn_metric", ["euclidean", "cosine", "manhattan"]),
"leaf_size": hp.choice("knn_leaf_size", [20, 30, 50]),
},
"supports_sample_weight": False
},
}
return spaces
def _build_preprocessor(self, pca_components: Any = None) -> Pipeline:
steps = [("scaler", StandardScaler())]
if pca_components is not None:
steps.append(("pca", PCA(n_components=pca_components)))
return Pipeline(steps)
def _create_objective(
self,
X: np.ndarray,
y: np.ndarray,
model_class,
static_params: Dict,
cv,
groups: Optional[np.ndarray] = None,
sample_weights: Optional[np.ndarray] = None,
supports_sample_weight: bool = True,
skip_pca: bool = False,
):
def objective(params):
if skip_pca:
pca_components = None
model_params = params
else:
pca_components = params.get("pca_components", None)
model_params = {k: v for k, v in params.items() if k != "pca_components"}
all_params = {**static_params, **model_params}
model = model_class(**all_params)
if skip_pca:
preprocessor = Pipeline([("scaler", StandardScaler())])
else:
preprocessor = self._build_preprocessor(pca_components)
pipeline = Pipeline([("preprocessor", preprocessor), ("model", model)])
params = {}
if sample_weights is not None and supports_sample_weight:
params["model__sample_weight"] = sample_weights
if groups is not None:
scores = cross_val_score(
pipeline, X, y, cv=cv, scoring=self.scoring,
n_jobs=1 if model_class == ResNet18Classifier else -1,
groups=groups, params=params if params else None
)
else:
scores = cross_val_score(
pipeline, X, y, cv=cv, scoring=self.scoring,
n_jobs=1 if model_class == ResNet18Classifier else -1,
params=params if params else None
)
return {
"loss": -scores.mean(),
"status": STATUS_OK,
"score_mean": scores.mean(),
"score_std": scores.std(),
"fold_scores": scores.tolist(),
"pca_components": pca_components
}
return objective
def tune_model(
self,
X: np.ndarray,
y: np.ndarray,
model_name: str,
max_evals: int = 100,
cv=None,
groups: Optional[np.ndarray] = None,
sample_weights: Optional[np.ndarray] = None,
use_pca: bool = True,
) -> Dict[str, Any]:
"""Tune a single model using Hyperopt."""
spaces = self.get_hyperopt_spaces()
if model_name not in spaces:
raise ValueError(f"Unknown model: {model_name}. Available: {list(spaces.keys())}")
config = spaces[model_name]
supports_sample_weight = config.get("supports_sample_weight", True)
skip_pca = config.get("skip_pca", False)
space = config["space"].copy()
if use_pca and not skip_pca:
space["pca_components"] = hp.choice(f"{model_name}_pca", [None, 0.90, 0.95, 0.99, 50, 100, 200])
if cv is None:
if groups is not None:
cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=self.random_state)
else:
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=self.random_state)
cv_type = "StratifiedGroupKFold" if groups is not None else "StratifiedKFold"
print(f"\n{'=' * 60}")
print(f"Hyperopt Tuning: {model_name}")
print(f" Scoring: {self.scoring}")
print(f" Max evaluations: {max_evals}")
print(f" CV strategy: {cv_type} with {cv.n_splits} folds")
print(f" Using sample weights: {sample_weights is not None and supports_sample_weight}")
print(f" PCA search: {use_pca and not skip_pca}")
print(f"{'=' * 60}")
objective = self._create_objective(
X, y, config["model_class"], config["static_params"], cv,
groups=groups, sample_weights=sample_weights,
supports_sample_weight=supports_sample_weight, skip_pca=skip_pca,
)
trials = Trials()
best_indices = fmin(
fn=objective, space=space, algo=tpe.suggest, max_evals=max_evals,
trials=trials, rstate=np.random.default_rng(self.random_state),
show_progressbar=True
)
best_params = space_eval(space, best_indices)
best_trial = trials.best_trial
best_score = best_trial["result"]["score_mean"]
best_score_std = best_trial["result"]["score_std"]
pca_components = best_params.pop("pca_components", None) if not skip_pca else None
final_params = {**config["static_params"], **best_params}
final_model = config["model_class"](**final_params)
if skip_pca:
preprocessor = Pipeline([("scaler", StandardScaler())])
else:
preprocessor = self._build_preprocessor(pca_components)
final_pipeline = Pipeline([("preprocessor", preprocessor), ("model", final_model)])
if sample_weights is not None and supports_sample_weight:
final_pipeline.fit(X, y, model__sample_weight=sample_weights)
else:
final_pipeline.fit(X, y)
# Extract trial history for plotting
trial_history = []
for i, trial in enumerate(trials.trials):
trial_history.append({
"trial": i + 1,
"score": trial["result"]["score_mean"],
"std": trial["result"]["score_std"],
"loss": trial["result"]["loss"]
})
result = {
"model_name": model_name,
"best_params": best_params,
"best_params_with_static": final_params,
"pca_components": pca_components,
"cv_score_mean": best_score,
"cv_score_std": best_score_std,
"scoring_metric": self.scoring,
"best_estimator": final_pipeline,
"trials": trials,
"trial_history": trial_history,
"n_evals": len(trials.trials),
"used_sample_weights": sample_weights is not None and supports_sample_weight,
"cv_strategy": cv_type
}
print(f"\n ✓ Best params: {best_params}")
if not skip_pca:
print(f" ✓ PCA components: {pca_components}")
print(f" ✓ CV {self.scoring}: {best_score:.4f} (+/- {best_score_std:.4f})")
return result
def tune_all_models(