1. CIC-IDS-2017数据集简介与下载CIC-IDS-2017是加拿大网络安全研究所发布的一个经典网络入侵检测数据集它模拟了真实企业网络环境中的正常流量和多种攻击行为。这个数据集最大的特点是包含了完整的网络流量包PCAP格式和已经提取好的特征文件CSV格式特别适合用来训练机器学习模型进行异常流量检测。数据集采集于2017年7月3日到7月7日的工作日期间每天模拟不同的网络场景周一仅包含正常流量周二暴力破解FTP/SSH攻击周三DoS攻击和端口扫描周四Web攻击和渗透测试周五DDoS攻击和僵尸网络活动下载数据集时你会看到8个主要的CSV文件每个对应不同时段的网络活动。我建议直接从加拿大网络安全研究所官网下载完整压缩包约3GB解压后会得到这些关键文件Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv Friday-WorkingHours-Morning.pcap_ISCX.csv Monday-WorkingHours.pcap_ISCX.csv Thursday-WorkingHours-Afternoon-Infilteration.pcap_ISCX.csv Thursday-WorkingHours-Morning-WebAttacks.pcap_ISCX.csv Tuesday-WorkingHours.pcap_ISCX.csv Wednesday-workingHours.pcap_ISCX.csv2. 数据预处理完整流程2.1 初始数据检查与特征行处理刚拿到原始CSV文件时我习惯先用pandas快速浏览数据结构import pandas as pd file_path Friday-WorkingHours-Morning.pcap_ISCX.csv raw_data pd.read_csv(file_path) print(raw_data.head(3))你会发现第一行其实是特征描述比如Flow Duration、Total Fwd Packets等而不是真正的数据。这会导致pandas把特征名误认为第一行数据。我的处理方法是# 跳过第一行读取并手动添加列名 with open(file_path) as f: columns f.readline().strip().split(,) data pd.read_csv(file_path, skiprows1, headerNone, namescolumns)2.2 缺失值处理实战技巧这个数据集常见的缺失值表现为NaN、Infinity或空字符串。我推荐组合使用以下方法# 替换无穷大值 import numpy as np data.replace([np.inf, -np.inf], np.nan, inplaceTrue) # 删除缺失值超过50%的列 threshold len(data) * 0.5 data data.dropna(threshthreshold, axis1) # 对剩余缺失值用中位数填充 numeric_cols data.select_dtypes(includenp.number).columns for col in numeric_cols: data[col].fillna(data[col].median(), inplaceTrue)特别注意某些特征列如Flow Bytes/s在除数为零时会产生无穷大值这类列需要特殊处理。2.3 标签编码的工程实践原始数据中的攻击标签是文本形式如BENIGN、DDoS等需要转换为数值。我建议采用两种方案方案一简单标签编码from sklearn.preprocessing import LabelEncoder le LabelEncoder() data[Label] le.fit_transform(data[Label])方案二自定义优先级编码label_priority { BENIGN: 0, PortScan: 1, DDoS: 2, # 其他攻击类型... } data[Label] data[Label].map(label_priority)第二种方法特别适合需要区分攻击严重程度的场景。记得保存编码映射关系后续预测时需要反向解码。3. 特征工程关键步骤3.1 特征选择与降维原始数据集包含80多个特征很多存在高度相关性。我通常先做相关性分析import seaborn as sns corr_matrix data.corr().abs() plt.figure(figsize(20,15)) sns.heatmap(corr_matrix, annotFalse) plt.show()然后使用方差阈值法过滤低方差特征from sklearn.feature_selection import VarianceThreshold selector VarianceThreshold(threshold0.1) selected_features selector.fit_transform(data[numeric_cols])3.2 特征归一化实战不同特征的量纲差异极大比如数据包数量可能是几千而持续时间是毫秒级必须进行归一化。我常用的三种方法Min-Max归一化适合均匀分布from sklearn.preprocessing import MinMaxScaler scaler MinMaxScaler() scaled_data scaler.fit_transform(data[numeric_cols])Z-Score标准化适合存在异常值from sklearn.preprocessing import StandardScaler scaler StandardScaler() scaled_data scaler.fit_transform(data[numeric_cols])Robust Scaling对异常值更鲁棒from sklearn.preprocessing import RobustScaler scaler RobustScaler() scaled_data scaler.fit_transform(data[numeric_cols])4. 数据集划分与保存4.1 时间序列敏感的分割方法由于网络攻击具有时间相关性我建议按时间顺序划分数据集而非随机分割split_idx int(len(data)*0.7) train data.iloc[:split_idx] test data.iloc[split_idx:]4.2 高效存储预处理结果处理好的数据集建议保存为多种格式# 保存为CSV train.to_csv(train_processed.csv, indexFalse) # 保存为HDF5适合大数据集 train.to_hdf(train_processed.h5, keydata, modew) # 保存为Pickle保留数据类型 import pickle with open(train_processed.pkl, wb) as f: pickle.dump(train, f)5. 实际应用中的经验分享在多个实际项目中处理这个数据集后我总结出几个关键经验内存优化对于大文件可以使用chunksize参数分块读取chunk_iter pd.read_csv(file_path, chunksize50000) for chunk in chunk_iter: process(chunk)并行处理对于特征计算可以使用多核加速from joblib import Parallel, delayed results Parallel(n_jobs4)(delayed(compute_feature)(col) for col in data.columns)验证集构建建议从训练集中再划分20%作为验证集用于调参from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val train_test_split( train_features, train_labels, test_size0.2, stratifytrain_labels)类别不平衡处理攻击样本通常远少于正常流量需要采用过采样/欠采样from imblearn.over_sampling import SMOTE smote SMOTE() X_res, y_res smote.fit_resample(X_train, y_train)
CIC-IDS-2017数据集预处理实战:从原始流量到机器学习就绪数据
发布时间:2026/5/27 18:39:57
1. CIC-IDS-2017数据集简介与下载CIC-IDS-2017是加拿大网络安全研究所发布的一个经典网络入侵检测数据集它模拟了真实企业网络环境中的正常流量和多种攻击行为。这个数据集最大的特点是包含了完整的网络流量包PCAP格式和已经提取好的特征文件CSV格式特别适合用来训练机器学习模型进行异常流量检测。数据集采集于2017年7月3日到7月7日的工作日期间每天模拟不同的网络场景周一仅包含正常流量周二暴力破解FTP/SSH攻击周三DoS攻击和端口扫描周四Web攻击和渗透测试周五DDoS攻击和僵尸网络活动下载数据集时你会看到8个主要的CSV文件每个对应不同时段的网络活动。我建议直接从加拿大网络安全研究所官网下载完整压缩包约3GB解压后会得到这些关键文件Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv Friday-WorkingHours-Afternoon-PortScan.pcap_ISCX.csv Friday-WorkingHours-Morning.pcap_ISCX.csv Monday-WorkingHours.pcap_ISCX.csv Thursday-WorkingHours-Afternoon-Infilteration.pcap_ISCX.csv Thursday-WorkingHours-Morning-WebAttacks.pcap_ISCX.csv Tuesday-WorkingHours.pcap_ISCX.csv Wednesday-workingHours.pcap_ISCX.csv2. 数据预处理完整流程2.1 初始数据检查与特征行处理刚拿到原始CSV文件时我习惯先用pandas快速浏览数据结构import pandas as pd file_path Friday-WorkingHours-Morning.pcap_ISCX.csv raw_data pd.read_csv(file_path) print(raw_data.head(3))你会发现第一行其实是特征描述比如Flow Duration、Total Fwd Packets等而不是真正的数据。这会导致pandas把特征名误认为第一行数据。我的处理方法是# 跳过第一行读取并手动添加列名 with open(file_path) as f: columns f.readline().strip().split(,) data pd.read_csv(file_path, skiprows1, headerNone, namescolumns)2.2 缺失值处理实战技巧这个数据集常见的缺失值表现为NaN、Infinity或空字符串。我推荐组合使用以下方法# 替换无穷大值 import numpy as np data.replace([np.inf, -np.inf], np.nan, inplaceTrue) # 删除缺失值超过50%的列 threshold len(data) * 0.5 data data.dropna(threshthreshold, axis1) # 对剩余缺失值用中位数填充 numeric_cols data.select_dtypes(includenp.number).columns for col in numeric_cols: data[col].fillna(data[col].median(), inplaceTrue)特别注意某些特征列如Flow Bytes/s在除数为零时会产生无穷大值这类列需要特殊处理。2.3 标签编码的工程实践原始数据中的攻击标签是文本形式如BENIGN、DDoS等需要转换为数值。我建议采用两种方案方案一简单标签编码from sklearn.preprocessing import LabelEncoder le LabelEncoder() data[Label] le.fit_transform(data[Label])方案二自定义优先级编码label_priority { BENIGN: 0, PortScan: 1, DDoS: 2, # 其他攻击类型... } data[Label] data[Label].map(label_priority)第二种方法特别适合需要区分攻击严重程度的场景。记得保存编码映射关系后续预测时需要反向解码。3. 特征工程关键步骤3.1 特征选择与降维原始数据集包含80多个特征很多存在高度相关性。我通常先做相关性分析import seaborn as sns corr_matrix data.corr().abs() plt.figure(figsize(20,15)) sns.heatmap(corr_matrix, annotFalse) plt.show()然后使用方差阈值法过滤低方差特征from sklearn.feature_selection import VarianceThreshold selector VarianceThreshold(threshold0.1) selected_features selector.fit_transform(data[numeric_cols])3.2 特征归一化实战不同特征的量纲差异极大比如数据包数量可能是几千而持续时间是毫秒级必须进行归一化。我常用的三种方法Min-Max归一化适合均匀分布from sklearn.preprocessing import MinMaxScaler scaler MinMaxScaler() scaled_data scaler.fit_transform(data[numeric_cols])Z-Score标准化适合存在异常值from sklearn.preprocessing import StandardScaler scaler StandardScaler() scaled_data scaler.fit_transform(data[numeric_cols])Robust Scaling对异常值更鲁棒from sklearn.preprocessing import RobustScaler scaler RobustScaler() scaled_data scaler.fit_transform(data[numeric_cols])4. 数据集划分与保存4.1 时间序列敏感的分割方法由于网络攻击具有时间相关性我建议按时间顺序划分数据集而非随机分割split_idx int(len(data)*0.7) train data.iloc[:split_idx] test data.iloc[split_idx:]4.2 高效存储预处理结果处理好的数据集建议保存为多种格式# 保存为CSV train.to_csv(train_processed.csv, indexFalse) # 保存为HDF5适合大数据集 train.to_hdf(train_processed.h5, keydata, modew) # 保存为Pickle保留数据类型 import pickle with open(train_processed.pkl, wb) as f: pickle.dump(train, f)5. 实际应用中的经验分享在多个实际项目中处理这个数据集后我总结出几个关键经验内存优化对于大文件可以使用chunksize参数分块读取chunk_iter pd.read_csv(file_path, chunksize50000) for chunk in chunk_iter: process(chunk)并行处理对于特征计算可以使用多核加速from joblib import Parallel, delayed results Parallel(n_jobs4)(delayed(compute_feature)(col) for col in data.columns)验证集构建建议从训练集中再划分20%作为验证集用于调参from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val train_test_split( train_features, train_labels, test_size0.2, stratifytrain_labels)类别不平衡处理攻击样本通常远少于正常流量需要采用过采样/欠采样from imblearn.over_sampling import SMOTE smote SMOTE() X_res, y_res smote.fit_resample(X_train, y_train)