Valeri173

MoICyber-1

Nov 5th, 2025
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.58 KB | None | 0 0
  1. # Изисквания: pip install numpy pandas scikit-learn matplotlib
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.datasets import make_classification
  5. from sklearn.model_selection import train_test_split
  6. from sklearn.tree import DecisionTreeClassifier, plot_tree
  7. from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
  8. import matplotlib.pyplot as plt
  9.  
  10. # 1) Генериране на синтетични данни (симулиращи мрежови трафик)
  11. # Тук използваме make_classification: всеки ред = сесия/пакет; target = клас (напр. "злонамерен"/"нормален")
  12. X, y = make_classification(
  13.     n_samples=2000,       # брой примери
  14.     n_features=10,        # общ брой признаци (можеш да увеличиш по-нататък)
  15.     n_informative=6,      # колко признака са информативни за класа
  16.     n_redundant=2,        # линейно зависими признаци
  17.     n_repeated=0,
  18.     n_classes=2,          # бинарна класификация (например 0 = нормален, 1 = опасен)
  19.     weights=[0.8, 0.2],   # лек дисбаланс (80% нормални, 20% атаки)
  20.     class_sep=1.2,
  21.     random_state=42
  22. )
  23.  
  24. # 2) Зареждане в DataFrame чрез pandas
  25. feature_names = [f'feat_{i}' for i in range(X.shape[1])]
  26. df = pd.DataFrame(X, columns=feature_names)
  27. df['label'] = y
  28. print(df.head())
  29.  
  30. # 3) Разделяне на тренировъчен и тестов набор
  31. X = df[feature_names].values
  32. y = df['label'].values
  33. X_train, X_test, y_train, y_test = train_test_split(
  34.     X, y, test_size=0.3, stratify=y, random_state=42
  35. )
  36.  
  37. # 4) Използване на данните за обучение на Decision Tree
  38. clf = DecisionTreeClassifier(
  39.     criterion='gini',
  40.     max_depth=5,        # контролира простотата на дървото; пробвай различни стойности
  41.     min_samples_split=10,
  42.     random_state=42
  43. )
  44. clf.fit(X_train, y_train)
  45.  
  46. # 5) Начертаване на дървото
  47. plt.figure(figsize=(16,8))
  48. plot_tree(clf, feature_names=feature_names, class_names=['normal','attack'], filled=True, fontsize=8)
  49. plt.title("Decision Tree")
  50. plt.show()
  51.  
  52. # 6) Оценка на представянето върху тестовия масив
  53. y_pred = clf.predict(X_test)
  54. print("Accuracy:", accuracy_score(y_test, y_pred))
  55. print("Confusion matrix:\n", confusion_matrix(y_test, y_pred))
  56. print("Classification report:\n", classification_report(y_test, y_pred))
  57.  
  58. # 7) Проба със същото, но увеличаване на броя признаци
  59. # Генерираме нов набор с повече признаци (напр. 30)
  60. X2, y2 = make_classification(
  61.     n_samples=2000,
  62.     n_features=30,
  63.     n_informative=15,
  64.     n_redundant=10,
  65.     n_classes=2,
  66.     weights=[0.8, 0.2],
  67.     class_sep=1.0,
  68.     random_state=1
  69. )
  70. df2 = pd.DataFrame(X2, columns=[f'feat_{i}' for i in range(X2.shape[1])])
  71. df2['label'] = y2
  72.  
  73. X2 = df2.drop(columns=['label']).values
  74. y2 = df2['label'].values
  75. X2_train, X2_test, y2_train, y2_test = train_test_split(X2, y2, test_size=0.3, stratify=y2, random_state=1)
  76.  
  77. clf2 = DecisionTreeClassifier(max_depth=6, min_samples_split=10, random_state=1)
  78. clf2.fit(X2_train, y2_train)
  79.  
  80. y2_pred = clf2.predict(X2_test)
  81. print("With 30 features - Accuracy:", accuracy_score(y2_test, y2_pred))
  82. print("With 30 features - Classification report:\n", classification_report(y2_test, y2_pred))
Advertisement
Add Comment
Please, Sign In to add comment