Let’s create a simple machine learning program using the NSL-KDD dataset: 1. Install…
- User
Let’s create a simple machine learning program using the NSL-KDD dataset:
- Install required libraries:
pip install pandas scikit-learn
- Save the following code in a Python script (e.g., cyber_sec_ml.py):
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
Load the dataset
def load_dataset(url): column_names = [‘duration’, ‘protocol_type’, ‘service’, ‘flag’, ‘src_bytes’, ‘dst_bytes’, ‘land’, ‘wrong_fragment’, ‘urgent’, ‘hot’, ‘num_failed_logins’, ‘logged_in’, ‘num_compromised’, ‘root_shell’, ‘su_attempted’, ‘num_root’, ‘num_file_creations’, ‘num_shells’, ‘num_access_files’, ‘num_outbound_cmds’, ‘is_host_login’, ‘is_guest_login’, ‘count’, ‘srv_count’, ‘serror_rate’, ‘srv_serror_rate’, ‘rerror_rate’, ‘srv_rerror_rate’, ‘same_srv_rate’, ‘diff_srv_rate’, ‘srv_diff_host_rate’, ‘dst_host_count’, ‘dst_host_srv_count’, ‘dst_host_same_srv_rate’, ‘dst_host_diff_srv_rate’, ‘dst_host_same_src_port_rate’, ‘dst_host_srv_diff_host_rate’, ‘dst_host_serror_rate’, ‘dst_host_srv_serror_rate’, ‘dst_host_rerror_rate’, ‘dst_host_srv_rerror_rate’, ‘attack_type’, ‘difficulty_level’]
codedataset = pd.read_csv(url, header=None, names=column_names) return datasetEncode categorical features
def preprocess_data(dataset): categorical_features = [‘protocol_type’, ‘service’, ‘flag’]
codefor feature in categorical_features: dataset = pd.concat([dataset, pd.get_dummies(dataset[feature], prefix=feature)], axis=1) dataset.drop(feature, axis=1, inplace=True) return datasetLoad and preprocess the dataset
url = ‘https://raw.githubusercontent.com/defcom17/NSL_KDD/master/KDDTrain%2B.txt’ dataset = preprocess_data(load_dataset(url))
Split the dataset into features (X) and target (y) variables
X = dataset.drop([‘attack_type’, ‘difficulty_level’], axis=1) y = dataset[‘attack_type’]
Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
Train the model
clf = RandomForestClassifier(n_estimators=100, random_state=42) clf.fit(X_train, y_train)
- Assistant