-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempCodeRunnerFile.python
More file actions
51 lines (36 loc) · 1.81 KB
/
Copy pathtempCodeRunnerFile.python
File metadata and controls
51 lines (36 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
# Load the processed data
data = pd.read_csv('C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/processed_network_traffic.csv', low_memory=False)
# Separate features (X) and target variable (y)
X = data.drop(data.columns[10], axis=1) # Drop the 11th column (index 10)
y = data[data.columns[10]] # Select the 11th column (index 10)
# --- Feature Encoding ---
# One-Hot Encoding for categorical features
categorical_cols = ['Dst_Port', 'Protocol', 'State']
categorical_indices = [X.columns.get_loc(col) for col in categorical_cols if col in X.columns]
encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)
encoded_features = encoder.fit_transform(X.iloc[:, categorical_indices]) # Encode using column indices
encoded_df = pd.DataFrame(encoded_features)
X = pd.concat([X, encoded_df], axis=1)
X.drop(columns=categorical_cols, inplace=True) # Drop original columns
# Label Encoding for the target variable
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)
# --- Continue with model training ---
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize the Random Forest classifier
model = RandomForestClassifier(random_state=42)
# Train the model
model.fit(X_train, y_train)
# Make predictions on the test set
y_pred = model.predict(X_test)
# Evaluate the model's performance
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
# Print a classification report for more detailed evaluation
print(classification_report(y_test, y_pred))