You are a machine learning expert for classification problems.
Your task is to write Python code that executes the following instructions:
I provided a file containing linkings between SNORT rules and MITER ATT&CK Techniques. Each Rule is mapped to a list of MITER ATT&CK technique IDs.
Your job is to train a Machine Learning classifier on the data provided to you.
The Pipeline is expected to include the following: Distribute the data set in a balanced way into a training and test set. Extracting features relevant to the task according to the data you received and selecting significant features.
Examining several different models for a classification problem and performing cross validation.
Finally came up with and calculate the Precision, Recall and F1-score on the test set (macro)
Your goal is to maximize the evaluation indicators as much as possible (with an emphasis on F1-score)
Assistant
python
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC
from sklearn.metrics import precision_score, recall_score, f1_score
# Load the data
df = pd.read_csv("snort_rules_to_mitre_attack.csv") # Replace with your file name
# Preprocessing
# Assuming your data has a 'rule' column for SNORT rules and 'techniques' for a list of MITRE IDs
df['techniques'] = df['techniques'].str.split(',') # Convert string of IDs to list
# Feature extraction
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['rule'])
# Target variable transformation
mlb = MultiLabelBinarizer()
y = mlb.fit_transform(df['techniques'])
# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Model selection and hyperparameter tuning
models = {
'Logistic Regression': {
'model': OneVsRestClassifier(LogisticRegression()),
'params': {
'estimator__C': [0.1, 1, 10]
}
},
'Random Forest': {
'model': OneVsRestClassifier(RandomForestClassifier()),
'params': {
'estimator__n_estimators': [50, 100, 200],
'estimator__max_depth': [None, 5, 10]
}
},
'Linear SVC': {
'model': OneVsRestClassifier(LinearSVC()),
'params': {
'estimator__C': [0.1, 1, 10]
}
}
}
best_model = None
best_f1 = 0
for model_name, model_data in models.items():
print(f"Training {model_name}...")
clf = GridSearchCV(model_data['model'], model_data['params'], cv=5, scoring='f1_macro')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
f1 = f1_score(y_test, y_pred, average='macro')
print(f"{model_name} F1-score: {f1}")
if f1 > best_f1:
best_f1 = f1
best_model = clf
# Evaluation on the test set
y_pred = best_model.predict(X_test)
precision = precision_score(y_test, y_pred, average='macro')
recall = recall_score(y_test, y_pred, average='macro')
f1 = f1_score(y_test, y_pred, average='macro')
print("\nBest Model:", best_model.best_estimator_)
print("Precision:", precision)
print("Recall:", recall)
print("F1-score:", f1)
Explanation:
Data Loading and Preprocessing:
Load the CSV data into a Pandas DataFrame.
Assuming a column named 'techniques' contains a comma-separated string of MITRE IDs, convert it into a list of IDs.
Feature Extraction:
Use TfidfVectorizer to convert the SNORT rules (text) into numerical features using TF-IDF.
Target Variable Transformation:
Use MultiLabelBinarizer to transform the list of MITRE technique IDs into a multi-label binary format suitable for multi-label classification.
Data Splitting:
Split the data into training (80%) and testing (20%) sets using train_test_split.
Model Selection and Hyperparameter Tuning:
Define a dictionary models containing three different classification models (Logistic Regression, Random Forest, Linear SVC) along with their hyperparameter grids for tuning.
Use GridSearchCV with 5-fold cross-validation and 'f1_macro' scoring to find the best hyperparameters for each model.
Evaluation:
Train the best model from the grid search on the full training set.
Make predictions on the test set and calculate precision, recall, and F1-score (macro-averaged for multi-label classification).
Output:
Print the best model (with its hyperparameters), precision, recall, and F1-score on the test set.
Remember:
Replace "snort_rules_to_mitre_attack.csv" with the actual filename of your data.
Adjust the code if your data format is different (column names, data types).
Consider exploring other classification models and hyperparameter ranges for potentially better performance.
The emphasis on F1-score suggests finding a good balance between precision and recall. You can adjust the scoring metric in GridSearchCV if needed.