# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 18:24:27 2020

@author: Swaroop Sonte
"""

import pandas as pd
import numpy as np

#path to load malware data from .cvs file
targets_path = r"D:\Masters\Project\Android Datasets\Final Version\CDMC2017_T1_AndroidAPITrainData.csv"

label_path = r"D:\Masters\Project\Android Datasets\Final Version\CDMC2017_T1_AndroidAPITrainLabel.csv"

#reading data
target_data = pd.read_csv(targets_path, sep='delimiter', header=None, skip_blank_lines=False)  # , skip_blank_lines=False

label_data = pd.read_csv(label_path, header= None)

no_of_samples,_ = target_data.shape
#no_of_samples = 2000  # max 30875
target_data = np.asarray(target_data[0].iloc[0: no_of_samples])

label_data = np.asarray(label_data[0].iloc[0:no_of_samples])

#target_data = np.asarray(target_data)

target_data3 = []
for sample in target_data:
    #print(type(sample))
    #print(sample)
    target_data2= list([])
    target_data3.append(target_data2)
    for i in sample.split(" "):
        #print(i)
        target_data2.append(i)

target_data3 = np.asarray(target_data3)

new_data = np.zeros((no_of_samples,37107))

x = 0

while x < no_of_samples:
    
    for sample in target_data3:
        #print(type(sample))

        for i in sample:

            new_data[x, (int(i)-1)]=1
            
        x += 1

#importing necessary functions from sklearn
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
#from sklearn import cross_validation

Feature_extraction = ExtraTreesClassifier().fit(new_data, label_data)
Model = SelectFromModel(Feature_extraction, prefit=True)
Data_new = Model.transform(new_data)

X_train, X_test, y_train, y_test = train_test_split(Data_new, label_data, test_size=0.30)

from sklearn import svm

model = svm.SVC()

poly = svm.SVC(kernel='linear', degree=3, C=1, decision_function_shape='ovo').fit(X_train, y_train)

svm_predictions = poly.predict(X_test)

from sklearn.metrics import accuracy_score

svm_accuracy = accuracy_score(svm_predictions, y_test)

print("model accracy : " , accuracy_score(svm_predictions, y_test))

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

knn_scores = []

n = 10

for i in range(1,10):
    neigh = KNeighborsClassifier(i)
    neigh.fit(X_train, y_train)
    predictions = neigh.predict(X_test)
    
    score = accuracy_score(predictions, y_test)

    knn_scores.append(score)

import matplotlib.pyplot as plt

plot1 = plt.figure(1)
plt.title("knn accuracy for n = 1 to 10")
plt.xlabel("n value") 
plt.ylabel("accuracy") 
ax=plt.subplot(111)
ax.set_xlim(1, n-1)
plt.plot(knn_scores)



all_scores = [svm_accuracy, max(knn_scores)]
algorithms = ["svm", "knn"]
plot2 = plt.figure(2)
# creating the bar plot 
plt.bar(algorithms, all_scores, color ='maroon',  
        width = 0.4) 
plt.xlabel("Algorithms")
plt.ylabel("accuracy")
plt.title("Comparision between SVM and KNN") 
plt.show()

#np.savetxt("new_data1.csv", new_data, delimiter=",")

#new_d = pd.read_csv(r"U:\MalwareData.csv\new_data1.csv", header=None)
