6.2 KiB
6.2 KiB
In [ ]:
from pathlib import Path
import numpy as np
import pandas as pd
DATA_PATH = Path("data/cicids2017_binary_sample.csv")
RANDOM_STATE = 42
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
In [ ]:
df = pd.read_csv(DATA_PATH)
df.columns = df.columns.str.strip()
df = df.drop_duplicates().replace([np.inf, -np.inf], np.nan)
X = df.drop(columns="Label").select_dtypes(include="number")
y = df["Label"].astype(str).str.strip().str.upper().ne("BENIGN").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=RANDOM_STATE,
stratify=y,
)
In [ ]:
pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("model", RandomForestClassifier(
n_estimators=100,
max_depth=12,
random_state=RANDOM_STATE,
n_jobs=-1,
)),
])
print(pipeline)
In [ ]:
pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
print("Predictions:", y_pred[:20])
print("Number of test samples:", len(y_pred))
In [ ]:
one_flow = X_test.iloc[[0]]
one_prediction = int(pipeline.predict(one_flow)[0])
print("Prediction:", one_prediction)
print("Meaning:", "ATTACK" if one_prediction == 1 else "BENIGN")
In [ ]:
assert list(pipeline.named_steps) == ["imputer", "model"]
assert pipeline.named_steps["model"].n_estimators == 100
assert len(y_pred) == len(y_test)
assert set(np.unique(y_pred)).issubset({0, 1})
assert one_prediction in {0, 1}
print("✓ Lab 3 completed")
In [ ]:
In [ ]:
In [ ]:
In [ ]: