Advertisement
print623

CW_task4_kernel_SVM_with_Gridsearch

Dec 20th, 2023 (edited)
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | Cybersecurity | 0 0
  1. # Importing Libraries:
  2. from sklearn import svm
  3. import numpy as np
  4. from sklearn.model_selection import GridSearchCV, train_test_split
  5. from sklearn.metrics import make_scorer, f1_score
  6. #The script imports necessary libraries, including scikit-learn for the SVM model, NumPy for numerical operations, and matplotlib for plotting.
  7. # Loading Training Data:
  8. data = np.load('C:/Users/print15207/MATLAB Drive/Print HVDC/Smartgrid CW/train_dataset.npy',allow_pickle=True)
  9. #The training dataset is loaded from the specified NumPy file.
  10. # Extracting Features and Labels:
  11. x = data.item()['feature']
  12. y = data.item()['label']
  13. #The features (x) and labels (y) are extracted from the loaded data.
  14. # Splitting the Data into Training and Testing Sets:
  15. x1=x[:4800] #Only classify between class 0 (normal measurement) and class 1 (FDI attack measurement)
  16. y1=y[:4800]
  17. x_train, x_test, y_train, y_test = train_test_split(x1, y1, test_size=0.319, random_state=42)
  18. #The data is split into training and testing sets using train_test_split from scikit-learn.
  19. print("Training set size: ",x_train.shape)
  20. print("Testing set size: ",x_test.shape)
  21. # Define the SVM model
  22. svm_model = svm.SVC()
  23. # Define the hyperparameter grid to search
  24. param_grid = {
  25.     'C': [0.1, 1, 10, 100],
  26.     'gamma': [0.01, 0.1, 1, 10]
  27. }
  28. # Define F1 score as the evaluation metric for hyperparameter tuning
  29. scorer = make_scorer(f1_score)
  30. # Perform Grid Search with Cross Validation
  31. grid_search = GridSearchCV(estimator=svm_model, param_grid=param_grid, scoring=scorer, cv=5)
  32. grid_search.fit(x_train, y_train)
  33. # Print the best hyperparameters
  34. print("Best Hyperparameters:", grid_search.best_params_)
  35. # Evaluate the model with the best hyperparameters on the test set
  36. best_svm_model = grid_search.best_estimator_
  37. test_predictions = best_svm_model.predict(x_test)
  38. test_f1_score = f1_score(y_test, test_predictions)
  39. print("F1 Score on Test Set with Best Hyperparameters:", test_f1_score)
  40.  
  41. #results
  42. #Training set size:  (3268, 34)
  43. #Testing set size:  (1532, 34)
  44. #Best Hyperparameters: {'C': 10, 'gamma': 10}
  45. #F1 Score on Test Set with Best Hyperparameters: 0.999330207635633
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement