使用卷积神经网络(CNN)对DDoS攻击检测
·
引言
随着网络技术的发展,分布式拒绝服务(DDoS)攻击变得越来越普遍和复杂。传统的基于规则的检测方法已经无法有效应对这些攻击,因此需要更加智能和自动化的检测方法。本文将介绍如何使用卷积神经网络(CNN)来构建一个用于DDoS攻击检测的模型。
环境准备
首先,我们需要安装一些必要的库:
pip install tensorflow pandas numpy scikit-learn matplotlib seaborn
数据集来源
开源数据集
Kaggle
导入需要的库
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
数据预处理
在开始构建模型之前,我们需要对数据进行预处理。这包括加载数据、处理缺失值、归一化等步骤。以下是具体的代码实现:
class CNNForDDoSDetection:
def __init__(self, file_path):
self.file_path = file_path
self.model = None
self.history = None
def build_model(self, input_shape):
self.model = Sequential([
Input(shape=input_shape),
Conv1D(filters=32, kernel_size=3, activation='relu'),
BatchNormalization(),
MaxPooling1D(pool_size=2),
Dropout(0.2),
Conv1D(filters=64, kernel_size=3, activation='relu'),
BatchNormalization(),
MaxPooling1D(pool_size=2),
Dropout(0.3),
Conv1D(filters=128, kernel_size=3, activation='relu'),
BatchNormalization(),
MaxPooling1D(pool_size=2),
Dropout(0.4),
Flatten(),
Dense(256, activation='relu'),
Dropout(0.6),
Dense(1, activation='sigmoid')
])
加载数据
我们首先从CSV文件中加载数据:
def load_data(self):
data = pd.read_csv(self.file_path)
return data
数据预处理
接下来,我们对数据进行预处理,包括处理缺失值、归一化等:
def preprocess_data(self, data):
data.columns = data.columns.str.strip()
labels = data['Label']
features = data.drop(columns=['Label'])
features.replace([np.inf, -np.inf], np.nan, inplace=True)
max_threshold = 1e6
features[features > max_threshold] = max_threshold
imputer = SimpleImputer(strategy='mean')
features_imputed = imputer.fit_transform(features)
features_imputed = pd.DataFrame(features_imputed, columns=features.columns)
return features_imputed, labels
数据分割
我们将数据集分为训练集和测试集:
def split_data(self, features, labels):
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)
return X_train, X_test, y_train, y_test
模型构建与训练
接下来,我们构建CNN模型并进行训练:
def compile_and_train(self, X_train, y_train, input_shape):
self.build_model(input_shape)
self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
self.history = self.model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2)
模型评估与可视化
训练完成后,我们需要对模型进行评估,并将结果可视化:
def evaluate_model(self, X_test, y_test):
y_pred = self.model.predict(X_test)
y_pred = (y_pred > 0.5).astype(int)
report = classification_report(y_test, y_pred, target_names=['BENIGN', 'DDoS'])
matrix = confusion_matrix(y_test, y_pred)
results_file = 'jieguo.txt'
with open(results_file, 'w', encoding='utf-8') as f:
f.write("分类报告:\n" + report + "\n")
f.write("混淆矩阵:\n" + str(matrix) + "\n")
print(f"评估结果已保存到 {results_file}")
return report, matrix
混淆矩阵可视化
为了更直观地展示模型的性能,我们可以绘制混淆矩阵:
def visualize_confusion_matrix(self, y_true, y_pred, labels, save_path='image/混淆矩阵.png'):
cm = confusion_matrix(y_true, y_pred)
plt.rcParams['font.sans-serif'] = 'kaiti'
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=labels, yticklabels=labels)
plt.xlabel('预测标签')
plt.ylabel('真实标签')
plt.title('混淆矩阵')
plt.savefig(save_path, dpi=300)
print(f"混淆矩阵图片已保存到: {save_path}")
plt.show()
训练历史可视化
我们还可以将训练过程中的损失和准确率变化情况绘制出来:
def plot_training_history(self, save_path='image/训练历史曲线.png'):
plt.rcParams['font.sans-serif'] = 'kaiti'
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(self.history.history['loss'], label='训练损失')
plt.plot(self.history.history['val_loss'], label='验证损失')
plt.title('损失曲线')
plt.xlabel('训练轮次')
plt.ylabel('损失值')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(self.history.history['accuracy'], label='训练准确率')
plt.plot(self.history.history['val_accuracy'], label='验证准确率')
plt.title('准确率曲线')
plt.xlabel('训练轮次')
plt.ylabel('准确率')
plt.legend()
plt.tight_layout()
plt.savefig(save_path)
plt.show()
print(f"训练历史图已保存为: {save_path}")
模型保存
最后,我们将训练好的模型保存下来:
def save_model(self, save_path='model/cnn_ddos_model.h5'):
self.model.save(save_path)
print(f"模型已保存到: {save_path}")
运行整个流程
将所有步骤整合在一起,形成一个完整的运行流程:
def run(self):
data = self.load_data()
features, labels = self.preprocess_data(data)
X_train, X_test, y_train, y_test = self.split_data(features, labels)
input_shape = (X_train.shape[1], 1)
self.compile_and_train(X_train, y_train, input_shape)
y_pred = (self.model.predict(X_test) > 0.5).astype('int32')
self.evaluate_model(X_test, y_test)
self.visualize_confusion_matrix(y_test, y_pred, labels=['BENIGN', 'DDoS'])
self.plot_training_history()
self.save_model()
总结
通过本文的介绍,我们了解了如何使用卷积神经网络(CNN)来构建一个用于DDoS攻击检测的模型。从数据预处理、模型构建、训练到评估和可视化,每一步都进行了详细的讲解。希望这篇文章能够帮助你更好地理解和应用CNN进行DDoS攻击检测。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)