共计 2847 个字符,预计需要花费 8 分钟才能阅读完成。
背景介绍
CICIDS2017 是加拿大网络安全研究所发布的网络入侵检测基准数据集,包含正常流量和常见攻击类型(如 DDoS、Brute Force 等)。它在网络安全领域被广泛用于评估机器学习模型的性能,主要特点包括:

- 包含完整网络流量特征(78 个特征维度)
- 覆盖 7 天的真实网络行为数据
- 标注了 15 种攻击类型和正常流量
但原始数据存在三个典型问题:
- 严重类别不平衡:正常流量占比 85.56%,而 Web 攻击仅占 0.0016%
- 特征量纲差异大:如
Flow Duration范围是 0 -685 秒,而Packet Length Mean单位是字节 - 存在缺失值和冗余特征:约 3.2% 的记录存在 NaN 值,部分特征相关性高达 0.9
技术方案
数据预处理
- 缺失值处理:
- 连续特征用中位数填充(避免异常值影响)
- 离散特征用众数填充
-
代码示例:
from sklearn.impute import SimpleImputer # 连续特征 num_imputer = SimpleImputer(strategy='median') df[['Flow Duration','Total Fwd Packets']] = num_imputer.fit_transform(df[['Flow Duration','Total Fwd Packets']]) # 离散特征 cat_imputer = SimpleImputer(strategy='most_frequent') df[['Protocol','Fwd PSH Flags']] = cat_imputer.fit_transform(df[['Protocol','Fwd PSH Flags']]) -
特征标准化:
- 对基于距离的模型(如 SVM)使用 Z -Score 标准化
- 对神经网络使用 MinMax 归一化
-
代码示例:
from sklearn.preprocessing import StandardScaler, MinMaxScaler # 标准化 scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) # 归一化 minmax = MinMaxScaler() X_train_minmax = minmax.fit_transform(X_train) -
类别编码:
- 有序特征用 OrdinalEncoder
- 名义特征用 OneHotEncoder
- 代码示例:
from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse=False) protocol_encoded = encoder.fit_transform(df[['Protocol']])
特征工程
- 互信息法筛选特征:
- 计算每个特征与标签的互信息得分
- 保留 Top 30 特征(实验显示效果最佳)
-
代码示例:
from sklearn.feature_selection import mutual_info_classif mi_scores = mutual_info_classif(X, y, random_state=42) selected_features = X.columns[mi_scores.argsort()[-30:]] -
PCA 降维:
- 保留 95% 的方差解释率
- 代码示例:
from sklearn.decomposition import PCA pca = PCA(n_components=0.95, svd_solver='full') X_pca = pca.fit_transform(X_scaled)
数据增强
采用 SMOTE+Tomek Links 组合策略:
- 先用 SMOTE 生成少数类样本
- 再用 Tomek Links 清理类间噪声
- 代码示例:
from imblearn.combine import SMOTETomek smote_tomek = SMOTETomek(sampling_strategy='minority') X_res, y_res = smote_tomek.fit_resample(X, y)
模型构建
推荐使用 BiLSTM+Attention 架构的原因:
- 网络流量具有时序特性,LSTM 能捕捉前后包关系
- Attention 机制能突出关键攻击特征
- 代码框架:
from tensorflow.keras.layers import Bidirectional, LSTM, Attention inputs = Input(shape=(SEQ_LEN, FEAT_DIM)) x = Bidirectional(LSTM(64, return_sequences=True))(inputs) x = Attention()([x, x]) x = GlobalAvgPool1D()(x) outputs = Dense(num_classes, activation='softmax')(x)
性能优化
超参数调优
使用 Optuna 进行贝叶斯优化:
-
定义搜索空间:
def objective(trial): params = {'units': trial.suggest_int('units', 32, 256), 'lr': trial.suggest_float('lr', 1e-5, 1e-3, log=True) } model = build_model(**params) return train_model(model) -
运行优化:
study = optuna.create_study(direction='maximize') study.optimize(objective, n_trials=50)
模型解释
使用 SHAP 分析特征重要性:
import shap
explainer = shap.DeepExplainer(model, X_train[:100])
shap_values = explainer.shap_values(X_test[:10])
shap.summary_plot(shap_values, X_test[:10])
避坑指南
- 数据泄露防范:
- 先拆分训练测试集再做标准化
-
使用 Pipeline 封装预处理步骤
-
类别不平衡处理:
- 在损失函数中使用 class_weight 参数
-
代码示例:
class_weights = compute_class_weight('balanced', classes=np.unique(y), y=y) model.fit(X, y, class_weight=dict(enumerate(class_weights))) -
内存优化:
- 使用 tf.data.Dataset 代替 Numpy 数组
- 启用 GPU 混合精度训练
- 代码示例:
policy = tf.keras.mixed_precision.Policy('mixed_float16') tf.keras.mixed_precision.set_global_policy(policy)
总结与延伸
三个值得探索的方向:
- 在线学习:适应不断演变的攻击模式
- 联邦学习:在保护隐私的前提下协同训练
- 图神经网络:建模主机间的交互关系
正文完
