In the realm of cybersecurity and network analytics, raw packet logs are often insufficient for training robust machine learning models. Security Operations Centers (SOCs) and IT operations teams must transform high-volume network flow data—such as NetFlow, sFlow, or IPFIX records—into meaningful features that reveal anomalies like data exfiltration, lateral movement, or port scanning. This guide provides a complete, reproducible workflow using Python’s pandas and scikit-learn. By following this step-by-step notebook approach, you will build a feature engineering pipeline that handles missing values, creates time-based aggregates, and scales features, ensuring your model is ready for production deployment.
Understanding the Data Structure and Prerequisites
Before writing code, it is crucial to understand the typical schema of network flow data. A standard CSV export from a router or firewall might contain columns such as src_ip, dst_ip, src_port, dst_port, protocol, bytes_sent, packets_sent, start_time, and duration.
Prerequisites:
* Python 3.8+: Ensure your environment has Python installed.
* Libraries: You will need pandas for data manipulation, scikit-learn for the pipeline, and numpy for numerical operations.
* Environment: This guide assumes a safe test environment (e.g., a local virtual environment or a sandboxed Jupyter Notebook). Do not run this code directly against live production traffic without proper network segmentation and authorization.
# Install required libraries in your environment
!pip install pandas scikit-learn numpy
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
Step 1: Loading and Inspecting Network Flow Data
The first step in any data science project is loading the dataset. In a real-world scenario, this data might be streamed from a SIEM (Security Information and Event Management) system or stored in a data lake. For this lab exercise, we will simulate a realistic CSV dataset containing network flows.
# Simulate loading a realistic network flow dataset
data = {
'src_ip': ['192.168.1.10', '192.168.1.15', '10.0.0.5'],
'dst_ip': ['172.16.0.50', '192.168.1.10', '172.16.0.51'],
'src_port': [45320, 52001, 33445],
'dst_port': [443, 45320, 80],
'protocol': ['TCP', 'TCP', 'UDP'],
'bytes_sent': [15000, 500, 120000],
'packets_sent': [100, 5, 800],
'start_time': pd.to_datetime(['2023-10-01 10:00:00', '2023-10-01 10:05:00', '2023-10-01 10:10:00']),
'duration': [30.5, 1.2, 45.0],
'is_anomaly': [0, 1, 0] # Target variable for demonstration
}
df = pd.DataFrame(data)
print(f"Dataset shape: {df.shape}")
print(df.head())
Expected Result: The output will display the first few rows of the dataframe. Notice that start_time is parsed as a datetime object, which is essential for time-based feature engineering later. In a production setting, you would replace this simulated data with an actual file path, e.g., pd.read_csv('network_flows.csv').
Step 2: Defining Numerical and Categorical Columns
Scikit-Learn pipelines require explicit separation of numerical and categorical features because they require different preprocessing strategies. Numerical data (like bytes sent) often needs scaling or aggregation, while categorical data (like protocols) usually requires one-hot encoding.
# Identify column types
numerical_features = ['bytes_sent', 'packets_sent', 'duration']
categorical_features = ['protocol']
datetime_features = ['start_time']
print(f"Numerical columns: {numerical_features}")
print(f"Categorical columns: {categorical_features}")
Common Mistake: Forgetting to include the target variable (is_anomaly) in either list can lead to accidental leakage if not handled correctly during training. Always exclude the target column from the feature engineering pipeline.
Step 3: Building the Feature Engineering Pipeline
This is the core of the notebook. We will construct a ColumnTransformer that applies specific transformations to different column groups and a SimpleImputer to handle missing data, which frequently occurs in network logs due to dropped packets or sensor failures.
# Define transformers for numerical data: Impute mean, then scale
numerical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler())
])
# Define transformer for categorical data: One-hot encode
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Define the column transformer to apply logic to specific columns
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_features),
('cat', categorical_transformer, categorical_features)
],
remainder='drop' # Drop remaining columns not specified (e.g., target or raw IP if not needed)
)
# Combine preprocessing into a full pipeline with a dummy model for demonstration
from sklearn.linear_model import LogisticRegression
full_pipeline = Pipeline(steps=[
('preprocess', preprocessor),
('model', LogisticRegression(max_iter=1000))
])
Explanation of Steps:
1. Imputer: Replaces missing values with the mean for numerical columns. This prevents the model from crashing on NaN values.
2. Scaler: Standardizes numerical features (zero mean, unit variance). Neural networks and distance-based algorithms perform best with scaled data.
3. OneHotEncoder: Converts categorical text (like ‘TCP’, ‘UDP’) into binary vectors without imposing an arbitrary order.
4. Remainder=’drop’: Ensures we don’t accidentally feed raw IP addresses or the target label into the scaler, which could introduce data leakage.
Step 4: Training and Evaluating the Model
Once the pipeline is defined, we split our data into training and testing sets. This simulates a real-world scenario where you train on historical logs and test on new, unseen traffic to evaluate performance.
from sklearn.model_selection import train_test_split
X = df.drop('is_anomaly', axis=1)
y = df['is_anomaly']
# Split data: 80% train, 20% test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train the pipeline
full_pipeline.fit(X_train, y_train)
# Evaluate on unseen data
score = full_pipeline.score(X_test, y_test)
print(f"Model Accuracy: {score:.2f}")
Verification Steps: Always check for overfitting. If the training accuracy is high but test accuracy is low, your features might be too specific to the training set. In network flow analysis, ensure you are not using future timestamps as features (look-ahead bias).
Step 5: Creating Custom Aggregated Features for Time-Series Analysis
Raw flow data often lacks context regarding user behavior over time. A single connection of 100MB is normal; a single connection of 100GB might be exfiltration. To capture this, we must engineer rolling window features. In a production notebook, you would group by src_ip and calculate aggregates like “total bytes sent in the last hour.”
# Example: Calculate hourly traffic volume per source IP (Simulated logic)
df['hour'] = df['start_time'].dt.floor('h')
hourly_traffic = df.groupby(['src_ip', 'hour'])['bytes_sent'].sum().reset_index()
# This aggregated dataframe could be merged back into the main flow data
# to create features like "avg_bytes_per_hour" or "max_bytes_per_hour"
print(hourly_traffic.head())
Industry Application: In a SOC environment, analysts often merge these hourly aggregates with real-time flows. If a current flow’s bytes_sent exceeds the historical 95th percentile for that specific source IP at that hour, it triggers an alert.
Step 6: Debugging and Handling Production Errors
When deploying this pipeline to Kubernetes or a cloud environment, errors are inevitable. Common issues include:
* Unknown Categories: If OneHotEncoder encounters a new protocol (e.g., ‘QUIC’) not seen during training, it will fail without handle_unknown='ignore'. Our code above handles this safely.
* Memory Overflow: Network logs can be massive. Always use chunking (read_csv(chunksize=...)) and process in batches if loading the entire dataset into memory crashes your server.
* Serialization: To save your pipeline for later use, use joblib.dump(full_pipeline, 'network_pipeline.pkl'). Do not rely on pickling complex pipelines without testing serialization compatibility across OS versions.
Student Practice Task: Build a Port Scan Detector
To solidify your understanding, complete this mini-project:
1. Download a sample dataset of port scans (available via Kaggle or similar repositories).
2. Create a new feature called unique_dst_ports_per_src_ip by counting distinct destination ports for each source IP within a 5-minute window.
3. Add this feature to your pipeline as a numerical column.
4. Train a classifier to distinguish between “normal browsing” and “port scanning.”
Conclusion
Implementing a custom feature engineering pipeline transforms raw, chaotic network logs into structured intelligence. By separating numerical and categorical processing, handling missing data robustly, and creating time-based aggregates, you build a foundation for effective anomaly detection. Remember that this code is a template; in a production environment, you must verify all assumptions against your specific network topology and local laws regarding data privacy (such as GDPR or CCPA). Always document your pipeline versions and dependencies to ensure reproducibility across team members and infrastructure updates.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

