Skip to main content

GBoostLyTec - Deteksi Anomali Unsupervised dengan Gradient Boosting

Python Version License Version

GBoostLyTec adalah library Python untuk deteksi anomali unsupervised yang menggabungkan algoritma gradient boosting dengan hybrid residual, loss functions yang dapat dikonfigurasi, iterative cleaning, dan ensemble voting.

Fitur Utama

  • Unsupervised: Tidak memerlukan label data
  • Hybrid Residual: Menggabungkan reconstruction error dan neighborhood deviation
  • Loss Functions Fleksibel: Squared error, robust (Huber), atau quantile
  • Iterative Cleaning: Pembersihan data progresif setiap iterasi
  • Subspace Boosting: Random feature selection untuk setiap weak learner
  • Ensemble Voting: Consensus-based anomaly scoring
  • Mahalanobis Distance: Memperhitungkan struktur covariance features
  • Scikit-learn Compatible: API yang familiar dan mudah digunakan

Instalasi

Dari PyPI

pip install gboostlytec

Quick Start

Penggunaan Dasar

from gboostlytec import GBoostLyTec
import numpy as np

# Data Anda (unsupervised - tidak perlu label!)
X = np.random.randn(500, 10)

# Inisialisasi model
model = GBoostLyTec(n_estimators=30, loss_type='robust')

# Training
model.fit(X)

# Prediksi
anomaly_scores, anomaly_labels = model.predict(X)

print(f"Anomali terdeteksi: {anomaly_labels.sum()}")
print(f"Mean anomaly score: {anomaly_scores.mean():.4f}")

Dengan Evaluasi

from gboostlytec import GBoostLyTec
from gboostlytec.utils import generate_synthetic_data, evaluate_predictions

# Generate synthetic data dengan true labels untuk evaluasi
X, y_true = generate_synthetic_data(
    n_normal=500,
    n_anomalies=50,
    n_features=10,
    random_state=42
)

# Train model
model = GBoostLyTec(n_estimators=30, loss_type='robust', random_state=42)
model.fit(X)

# Prediksi
scores, labels = model.predict(X)

# Evaluasi
metrics = evaluate_predictions(y_true, labels, scores, verbose=True)

Hyperparameter

model = GBoostLyTec(
    # Boosting parameters
    n_estimators=30,           # Jumlah iterasi boosting
    learning_rate=0.05,        # Learning rate awal
    adaptive_lr=True,          # Adaptive decay learning rate
    
    # Residual computation
    alpha=0.6,                 # Bobot reconstruction vs neighborhood
    n_neighbors=5,             # Neighbors untuk neighborhood deviation
    
    # Loss function 
    loss_type='robust',        # 'squared_error', 'robust', atau 'quantile'
    robust_loss_delta=1.0,     # Delta untuk Huber loss
    quantile_level=0.95,       # Quantile level
    
    # Decision Tree
    max_depth=4,               # Kedalaman tree maksimal
    min_samples_split=10,      # Minimum samples untuk split
    
    # Cleaning strategy
    cleaning_rate=0.05,        # Fraksi anomali dihapus per iterasi
    
    # Reproducibility
    random_state=42,           # Random seed
    verbose=1                  # Print progress
)

API Reference

fit(X)

model.fit(X)

Latih model pada data unsupervised.

Parameter:

  • X (array-like, shape (n_samples, n_features)): Data training

Return: self

predict(X)

anomaly_scores, anomaly_labels = model.predict(X)

Prediksi anomaly scores dan binary labels.

Return:

  • anomaly_scores (array, shape (n_samples,)): Scores [0, 1]
  • anomaly_labels (array, shape (n_samples,)): Labels 0/1

decision_function(X)

scores = model.decision_function(X)

Hitung anomaly scores saja.

predict_proba(X)

proba = model.predict_proba(X)

Return probability estimates [P(normal), P(anomali)].

get_summary()

summary = model.get_summary()

Dapatkan training statistics.

Utility Functions

generate_synthetic_data()

X, y_true = generate_synthetic_data(
    n_normal=500,
    n_anomalies=50,
    n_features=10,
    random_state=42
)

evaluate_predictions()

metrics = evaluate_predictions(
    y_true, 
    y_pred, 
    y_scores=None, 
    verbose=True
)

Contoh Real-World

Deteksi Anomali pada Data Transaksi

import pandas as pd
from gboostlytec import GBoostLyTec

# Load data transaksi
df = pd.read_csv('transactions.csv')

# Feature selection dan preprocessing
features = ['amount', 'duration', 'merchant_count', ...]
X = df[features].values

# Normalisasi (GBoostLyTec melakukan standardisasi otomatis)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Deteksi anomali
model = GBoostLyTec(n_estimators=50, loss_type='robust')
model.fit(X_scaled)

scores, labels = model.predict(X_scaled)

# Add hasil ke dataframe
df['anomaly_score'] = scores
df['is_anomaly'] = labels

# Filter anomali
suspicious_transactions = df[df['is_anomaly'] == 1]
print(f"Transaksi mencurigakan: {suspicious_transactions.shape[0]}")

Performa

Pada synthetic dataset (550 samples, 50 anomali):

  • Precision: 0.8364
  • Recall: 0.9200
  • F1-Score: 0.8762
  • ROC-AUC: 0.9510
  • Training Time: ~2 detik

Cara Memilih Hyperparameter

Loss Function

  • squared_error: Default, general purpose, sensitif outlier
  • robust: Recommended jika ada extreme outliers
  • quantile: Fokus pada tail distribution

Alpha

  • 0.7-0.9: Emphasize global reconstruction patterns
  • 0.3-0.5: Emphasize local neighborhood patterns
  • 0.5-0.6: Balanced (recommended)

n_estimators

  • 10-20: Fast, exploratory analysis
  • 30-50: Balanced speed vs accuracy (recommended)
  • 100+: More accurate, slower

License

Project ini menggunakan MIT License

Release files for gboostlytec 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gboostlytec 0.1.1
File Size Uploaded
gboostlytec-0.1.1.tar.gz 12.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for gboostlytec 0.1.1
File Interpreter ABI Platform
gboostlytec-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 22.6 kB

Release files / gboostlytec-0.1.1.tar.gz

Download URL gboostlytec-0.1.1.tar.gz
Size 12.2 kB
Tags Source
SHA-256 checksum
How to use checksums
c11c9a9ecfeb1cf4ed540d66570c7025de09973e3b150217ea6c99c124ecfbed
BLAKE2b-256 checksum
How to use checksums
0588c5334cfae474cd584983cd3ddc3e13c17e650a142c618ac633a1733a377f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Release files / gboostlytec-0.1.1-py3-none-any.whl

Download URL gboostlytec-0.1.1-py3-none-any.whl
Size 10.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3a054997765601877f5c6e70e00624e1b0fee8f5481c14cba50f1e06af8502b5
BLAKE2b-256 checksum
How to use checksums
904e1e628b4a00212273f2b8779a011711f56cdfdf8224765f988d8937dbe350
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Release history Release notifications | RSS feed

0.1.2

2 release files

This release

0.1.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page