基于NSL-KDD数据集实现入侵检测python代码
时间: 2024-02-03 11:04:23 浏览: 244
好的,以下是基于NSL-KDD数据集实现入侵检测的Python代码:
```python
# 导入需要的库和模块
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report
from keras.models import Sequential
from keras.layers import Dense, Dropout
# 读取NSL-KDD数据集
data = pd.read_csv('KDDTrain+.txt', header=None)
# 将标签列转换成0和1
data[41] = data[41].apply(lambda x: 0 if x=='normal' else 1)
# 将数据集分为特征和标签
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 将特征进行标准化
sc = StandardScaler()
X = sc.fit_transform(X)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建神经网络模型
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=X_train.shape[1]))
model.add(Dropout(0.5))
model.add(Dense(units=32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))
# 预测测试集
y_pred = model.predict(X_test)
y_pred = (y_pred > 0.5).astype(int)
# 打印分类报告
print(classification_report(y_test, y_pred))
```
注意,此代码需要Keras和Scikit-learn库。并且,需要将数据集文件KDDTrain+.txt与代码文件放在同一目录下。
阅读全文