Gid

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

# importing pandas

import numpy as np
import pandas as pd
from pandas.core.internals.blocks import F

pip install --upgrade scikit-learn

import numpy as np
import pandas as pd
from datetime import datetime

from sklearn.model_selection import train_test_split


from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix
#from sklearn.metrics import plot_confusion_matrix
from sklearn import tree
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from sklearn import neighbors, datasets
#from sklearn.inspection import DecisionBoundaryDisplay

import sklearn.metrics
from sklearn import metrics
from sklearn.metrics import f1_score
from sklearn.metrics import mean_squared_error

import matplotlib.pyplot as plt

from sklearn import preprocessing


label_encoder = preprocessing.LabelEncoder()

#AttackFree= [0:2369397]
#DoS= [0:656578]
#Fuzzy= )[0:591989]
#Impersonation= [0:995471]

AttackFree=
pd.read_csv('/content/drive/MyDrive/CAN_VehicleAttack_ML/CAN_vehicleAttack_
dataset1/CAN_Attack_dataset1-15F/CAN_Attack_dataset1_15
F/github_folder/extracted feature/CAN_attack_dataset1/Attack_free new.csv')
[0:236939]
DoS=
pd.read_csv('/content/drive/MyDrive/CAN_VehicleAttack_ML/CAN_vehicleAttack_
dataset1/CAN_Attack_dataset1-15F/CAN_Attack_dataset1_15
F/github_folder/extracted feature/CAN_attack_dataset1/DoS_Attack_new.csv')
[0:65657]
Fuzzy=
pd.read_csv('/content/drive/MyDrive/CAN_VehicleAttack_ML/CAN_vehicleAttack_
dataset1/CAN_Attack_dataset1-15F/CAN_Attack_dataset1_15
F/github_folder/extracted
feature/CAN_attack_dataset1/Fuzzy_Attack_New.csv')[0:59198]
Impersonation=
pd.read_csv('/content/drive/MyDrive/CAN_VehicleAttack_ML/CAN_vehicleAttack_
dataset1/CAN_Attack_dataset1-1

#Class1: Attack-Free

AttackFree.iloc[:, 1]= label_encoder.fit_transform(AttackFree.iloc[:, 1])


AttackFree.iloc[:, 2]= label_encoder.fit_transform(AttackFree.iloc[:, 2])
AttackFree.iloc[:, 3]= label_encoder.fit_transform(AttackFree.iloc[:, 3])
AttackFree.iloc[:, 4]= label_encoder.fit_transform(AttackFree.iloc[:, 4])
AttackFree.iloc[:, 5]= label_encoder.fit_transform(AttackFree.iloc[:, 5])
AttackFree.iloc[:, 6]= label_encoder.fit_transform(AttackFree.iloc[:, 6])
AttackFree.iloc[:, 7]= label_encoder.fit_transform(AttackFree.iloc[:, 7])
AttackFree.iloc[:, 8]= label_encoder.fit_transform(AttackFree.iloc[:, 8])
AttackFree.iloc[:, 9]= label_encoder.fit_transform(AttackFree.iloc[:, 9])
AttackFree.iloc[:, 10]= label_encoder.fit_transform(AttackFree.iloc[:, 10])
AttackFree.iloc[:, 11]= label_encoder.fit_transform(AttackFree.iloc[:, 11])
AttackFree.iloc[:, 12]= label_encoder.fit_transform(AttackFree.iloc[:, 12])
AttackFree.iloc[:, 13]= label_encoder.fit_transform(AttackFree.iloc[:, 13])
AttackFree.iloc[:, 14]= label_encoder.fit_transform(AttackFree.iloc[:, 14])
AttackFree.iloc[:, 15]= label_encoder.fit_transform(AttackFree.iloc[:, 15])
#AttackFree.iloc[:, 16]= label_encoder.fit_transform(AttackFree.iloc[:,
16])

#Class2: DoS

DoS.iloc[:, 1]= label_encoder.fit_transform(DoS.iloc[:, 1])


DoS.iloc[:, 2]= label_encoder.fit_transform(DoS.iloc[:, 2])
DoS.iloc[:, 3]= label_encoder.fit_transform(DoS.iloc[:, 3])
DoS.iloc[:, 4]= label_encoder.fit_transform(DoS.iloc[:, 4])
DoS.iloc[:, 5]= label_encoder.fit_transform(DoS.iloc[:, 5])
DoS.iloc[:, 6]= label_encoder.fit_transform(DoS.iloc[:, 6])
DoS.iloc[:, 7]= label_encoder.fit_transform(DoS.iloc[:, 7])
DoS.iloc[:, 8]= label_encoder.fit_transform(DoS.iloc[:, 8])
DoS.iloc[:, 9]= label_encoder.fit_transform(DoS.iloc[:, 9])
DoS.iloc[:, 10]= label_encoder.fit_transform(DoS.iloc[:, 10])
DoS.iloc[:, 11]= label_encoder.fit_transform(DoS.iloc[:, 11])
DoS.iloc[:, 12]= label_encoder.fit_transform(DoS.iloc[:, 12])
DoS.iloc[:, 13]= label_encoder.fit_transform(DoS.iloc[:, 13])
DoS.iloc[:, 14]= label_encoder.fit_transform(DoS.iloc[:, 14])
DoS.iloc[:, 15]= label_encoder.fit_transform(DoS.iloc[:, 15])
#DoS.iloc[:, 16]= label_encoder.fit_transform(DoS.iloc[:, 16])

#Class3: Fuzzy

Fuzzy.iloc[:, 1]= label_encoder.fit_transform(Fuzzy.iloc[:, 1])


Fuzzy.iloc[:, 2]= label_encoder.fit_transform(Fuzzy.iloc[:, 2])
Fuzzy.iloc[:, 3]= label_encoder.fit_transform(Fuzzy.iloc[:, 3])
Fuzzy.iloc[:, 4]= label_encoder.fit_transform(Fuzzy.iloc[:, 4])
Fuzzy.iloc[:, 5]= label_encoder.fit_transform(Fuzzy.iloc[:, 5])
Fuzzy.iloc[:, 6]= label_encoder.fit_transform(Fuzzy.iloc[:, 6])
Fuzzy.iloc[:, 7]= label_encoder.fit_transform(Fuzzy.iloc[:, 7])
Fuzzy.iloc[:, 8]= label_encoder.fit_transform(Fuzzy.iloc[:, 8])
Fuzzy.iloc[:, 9]= label_encoder.fit_transform(Fuzzy.iloc[:, 9])
Fuzzy.iloc[:, 10]= label_encoder.fit_transform(Fuzzy.iloc[:, 10])
Fuzzy.iloc[:, 11]= label_encoder.fit_transform(Fuzzy.iloc[:, 11])
Fuzzy.iloc[:, 12]= label_encoder.fit_transform(Fuzzy.iloc[:, 12])
Fuzzy.iloc[:, 13]= label_encoder.fit_transform(Fuzzy.iloc[:, 13])
Fuzzy.iloc[:, 14]= label_encoder.fit_transform(Fuzzy.iloc[:, 14])
Fuzzy.iloc[:, 15]= label_encoder.fit_transform(Fuzzy.iloc[:, 15])
#Fuzzy.iloc[:, 16]= label_encoder.fit_transform(Fuzzy.iloc[:, 16])

#Class4:Impersonation

Impersonation.iloc[:, 0]= label_encoder.fit_transform(Impersonation.iloc[:,


0])
Impersonation.iloc[:, 1]= label_encoder.fit_transform(Impersonation.iloc[:,
1])
Impersonation.iloc[:, 2]= label_encoder.fit_transform(Impersonation.iloc[:,
2])
Impersonation.iloc[:, 3]= label_encoder.fit_transform(Impersonation.iloc[:,
3])
Impersonation.iloc[:, 4]= label_encoder.fit_transform(Impersonation.iloc[:,
4])
Impersonation.iloc[:, 5]= label_encoder.fit_transform(Impersonation.iloc[:,
5])
Impersonation.iloc[:, 6]= label_encoder.fit_transform(Impersonation.iloc[:,
6])
Impersonation.iloc[:, 7]= label_encoder.fit_transform(Impersonation.iloc[:,
7])
Impersonation.iloc[:, 8]= label_encoder.fit_transform(Impersonation.iloc[:,
8])
Impersonation.iloc[:, 9]= label_encoder.fit_transform(Impersonation.iloc[:,
9])
Impersonation.iloc[:, 10]=
label_encoder.fit_transform(Impersonation.iloc[:, 10])
Impersonation.iloc[:, 11]=
label_encoder.fit_transform(Impersonation.iloc[:, 11])
Impersonation.iloc[:, 12]=
label_encoder.fit_transform(Impersonation.iloc[:, 12])
Impersonation.iloc[:, 13]=
label_encoder.fit_transform(Impersonation.iloc[:, 13])
Impersonation.iloc[:, 14]=
label_encoder.fit_transform(Impersonation.iloc[:, 14])
Impersonation.iloc[:, 15]=
label_encoder.fit_transform(Impersonation.iloc[:, 15])
#Impersonation.iloc[:, 16]=
label_encoder.fit_transform(Impersonation.iloc[:, 16])

label1 = []
for i in range(len(AttackFree)):
label1.append(1)

label2 = []
for i in range(len(DoS)):
label2.append(2)

label3 = []
for i in range(len(Fuzzy)):
label3.append(3)

label4 = []
for i in range(len(Impersonation)):
label4.append(4)

Dataset = np.concatenate((AttackFree, DoS, Fuzzy, Impersonation))


label = np.concatenate((label1, label2, label3, label4))

# Splitting the dataset into the Training set and Test set
X_Train, X_Test, Y_Train, Y_Test = train_test_split(Dataset, label,
test_size = 0.25, random_state = 0)

# Feature Scaling
sc_X = StandardScaler()
X_Train = sc_X.fit_transform(X_Train)
X_Test = sc_X.transform(X_Test)
# do your work here

# SVM Classifier

#Fitting the classifier into the Training set:SVM Training


#kernel = precomputed, rbf,linear,polynomial, poly
classifier_svm = SVC(kernel = 'rbf', gamma='scale',random_state = 0,
max_iter=-1, tol=0.0001,degree=3, verbose=False, class_weight=None,
C=100.0)

start_time_1 = datetime.now()

classifier_svm.fit(X_Train, Y_Train)

end_time_1 = datetime.now()
print('Training Duration: {}'.format(end_time_1 - start_time_1))

# SVM Testing
start_time_2 = datetime.now()
# Predicting the test set results
Y_Pred_svm = classifier_svm.predict(X_Test)

end_time_2 = datetime.now()
print('Testing Duration: {}'.format(end_time_2 - start_time_2))

# Making the Confusion Matrix :SVM


cm_svm = confusion_matrix(Y_Test, Y_Pred_svm)
cm_svm

import seaborn as sn
import matplotlib.pyplot as plt

font = {'family' : 'normal',


'size' : 14}

plt.rc('font', **font)

label = ['AttackFree', 'DoS', 'Fuzzy', 'Impersonation']

df_cm_svm = pd.DataFrame(cm_svm, index = [i for i in label],


columns = [i for i in label])

plt.figure(figsize = (7,5))
sn.heatmap(df_cm_svm, annot=True, fmt='.0f', cmap='Blues')
plt.ylabel('True Class')
plt.xlabel('Predicted Class')
plt.show()

#evaluation for SVM

print("Accuracy:",metrics.accuracy_score(Y_Test, Y_Pred_svm))
print("Precision:",metrics.precision_score(Y_Test, Y_Pred_svm,
average='micro'))
print("Recall:",metrics.recall_score(Y_Test, Y_Test, average='micro'))
print("F1_Score:",metrics.f1_score(Y_Test, Y_Test, average='micro'))
print("Cohen_Kappa_Score:",sklearn.metrics.cohen_kappa_score(Y_Test,
Y_Pred_svm, labels=None, weights=None, sample_weight=None))
#print("MSE:",metrics.mean_squared_error(Y_Test,Y_Pred_svm))

# Individual Clasification- SVM

print(classification_report(Y_Test, Y_Pred_svm))
#DT classifier
# Fitting the classifier into the Training set:Decision Tree (DT) Training

classifier_dt = tree.DecisionTreeClassifier(criterion='gini',
splitter='best',random_state=0, max_depth=None)

start_time_1 = datetime.now()

classifier_dt.fit(X_Train, Y_Train)

end_time_1 = datetime.now()
print('Training Duration: {}'.format(end_time_1 - start_time_1))

#DT Testing
start_time_2 = datetime.now()
# Predicting the test set results
Y_Pred_dt = classifier_dt.predict(X_Test)

end_time_2 = datetime.now()
print('Testing Duration: {}'.format(end_time_2 - start_time_2))
Y_Pred_dt

# Making the Confusion Matrix :DT


cm_dt = confusion_matrix(Y_Test, Y_Pred_dt)
cm_dt

import seaborn as sn
import matplotlib.pyplot as plt

font = {'family' : 'normal',


'size' : 14}

plt.rc('font', **font)

label = ['AttackFree', 'DoS', 'Fuzzy', 'Impersonation']

df_cm_dt = pd.DataFrame(cm_dt, index = [i for i in label],


columns = [i for i in label])

plt.figure(figsize = (7,5))
sn.heatmap(df_cm_dt, annot=True, fmt='.0f', cmap='Blues')
plt.ylabel('True Class')
plt.xlabel('Predicted Class')
plt.show()

#evaluation for DT

print("Accuracy:",metrics.accuracy_score(Y_Test, Y_Pred_dt))
print("Precision:",metrics.precision_score(Y_Test, Y_Pred_dt,
average='micro'))
print("Recall:",metrics.recall_score(Y_Test, Y_Test, average='micro'))
print("F1_Score:",metrics.f1_score(Y_Test, Y_Test, average='micro'))
print("Cohen_Kappa_Score:",sklearn.metrics.cohen_kappa_score(Y_Test,
Y_Pred_dt, labels=None, weights=None, sample_weight=None))
#print("MSE:",metrics.mean_squared_error(Y_Test,Y_Pred_svm))

# Individual Clasification- DT
print(classification_report(Y_Test, Y_Pred_dt))

# KNN classifier
#Fitting the classifier into the Training set:K-nearest Neighbour Training
#(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2,
metric='minkowski', metric_params=None, n_jobs=None)
#metric (Manhattan Distance, minkowski distance, Euclidean Distance, Cosine
Distance, Jaccard Distance, Hamming Distance)
#n_neighbors = 20
classifier_knn = neighbors.KNeighborsClassifier(n_neighbors=5,
weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski',
metric_params=None, n_jobs=None)

start_time_1 = datetime.now()

classifier_knn.fit(X_Train, Y_Train)

end_time_1 = datetime.now()
print('Training Duration: {}'.format(end_time_1 - start_time_1))

# KNN Testing
start_time_2 = datetime.now()
# Predicting the test set results
Y_Pred_knn = classifier_knn.predict(X_Test)

end_time_2 = datetime.now()
print('Testing Duration: {}'.format(end_time_2 - start_time_2))

# Making the Confusion Matrix :knn


cm_knn = confusion_matrix(Y_Test, Y_Pred_knn)
cm_knn

import seaborn as sn
import matplotlib.pyplot as plt

font = {'family' : 'normal',


'size' : 14}

plt.rc('font', **font)

label = ['AttackFree', 'DoS', 'Fuzzy', 'Impersonation']

df_cm_knn = pd.DataFrame(cm_knn, index = [i for i in label],


columns = [i for i in label])

plt.figure(figsize = (7,5))
sn.heatmap(df_cm_knn, annot=True, fmt='.0f', cmap='Blues')
plt.ylabel('True Class')
plt.xlabel('Predicted Class')
plt.show()

#evaluation for KNN


print("Accuracy:",metrics.accuracy_score(Y_Test, Y_Pred_knn))
print("Precision:",metrics.precision_score(Y_Test, Y_Pred_knn,
average='micro'))
print("Recall:",metrics.recall_score(Y_Test, Y_Test, average='micro'))
print("F1_Score:",metrics.f1_score(Y_Test, Y_Test, average='micro'))
print("Cohen_Kappa_Score:",sklearn.metrics.cohen_kappa_score(Y_Test,
Y_Pred_knn, labels=None, weights=None, sample_weight=None))
#print("MSE:",metrics.mean_squared_error(Y_Test,Y_Pred_svm))

# Individual Clasification- KNN

print(classification_report(Y_Test, Y_Pred_knn))

You might also like