Team Ai
Apppublic

Sellibro/MalwareDetection_DeepLearning

sourceHugging Faceafl-3.0updated 4y agoView on Hugging Face
0likes
app.py97 linesDownload Raw Back to root
1#!/usr/bin/env python2# coding: utf-83 4# In[2]:5 6import gradio as gr7 8import os9import pandas as pd10from math import sqrt;11import numpy as np12import matplotlib.pyplot as plt13 #load packages for ANN14import tensorflow as tf15    16def malware_detection_DL (results, malicious_traffic, benign_traffic):17    plt.clf()18    if os.path.exists("accplot.png"):19        os.remove("accplot.png")20    else:21        pass22    if os.path.exists("lossplot.png"):23        os.remove("lossplot.png")24    else:25        pass  26    malicious_dataset = pd.read_csv(malicious_traffic)  #Importing Datasets 27    benign_dataset = pd.read_csv(benign_traffic)28    # Removing duplicated rows from benign_dataset (5380 rows removed)29    benign_dataset = benign_dataset[benign_dataset.duplicated(keep=False) == False]30    # Combining both datasets together31    all_flows = pd.concat([malicious_dataset, benign_dataset])32    # Reducing the size of the dataset to reduce the amount of time taken in training models33    reduced_dataset = all_flows.sample(38000)34    #dataset with columns with nan values dropped35    df = reduced_dataset.drop(reduced_dataset.columns[np.isnan(reduced_dataset).any()], axis=1)36    #### Isolating independent and dependent variables for training dataset37    reduced_y = df['isMalware']38    reduced_x = df.drop(['isMalware'], axis=1);39    # Splitting datasets into training and test data40    #x_train, x_test, y_train, y_test = train_test_split(reduced_x, reduced_y, test_size=0.2, random_state=42)41   42    #scale data between 0 and 143    #min_max_scaler = preprocessing.MinMaxScaler()44    #x_scale = min_max_scaler.fit_transform(reduced_x)45    # Splitting datasets into training and test data46    #x_train, x_test, y_train, y_test = train_test_split(x_scale, reduced_y, test_size=0.2, random_state=42)47    #type of layers in ann model is sequential, dense and uses relu activation 48    ann = tf.keras.models.Sequential()49    model = tf.keras.Sequential([50        tf.keras.layers.Dense(32, activation ='relu', input_shape=(373,)),51        tf.keras.layers.Dense(32, activation = 'relu'),52        tf.keras.layers.Dense(1, activation = 'sigmoid'),53    ])54    55    56    model.compile(optimizer ='adam', 57        loss = 'binary_crossentropy',58        metrics = ['accuracy'])59        #model.fit(x_train, y_train, batch_size=32, epochs = 150, validation_data=(x_test, y_test))60        #does not output epochs and gives evalutaion of validation data and history of losses and accuracy61    history = model.fit(reduced_x, reduced_y,validation_split=0.33, batch_size=32, epochs = 10,verbose=0)62    _, accuracy = model.evaluate(reduced_x, reduced_y)63        #return history.history64    if results=="Accuracy":65        #summarize history for accuracy66        plt.plot(history.history['accuracy'])67        plt.plot(history.history['val_accuracy'])68        plt.title('model accuracy')69        plt.ylabel('accuracy')70        plt.xlabel('epoch')71        plt.legend(['train', 'test'], loc='upper left')72        plt.savefig('accplot.png')73        return "accplot.png",accuracy74    else:75        # summarize history for loss76        plt.plot(history.history['loss'])77        plt.plot(history.history['val_loss'])78        plt.title('model loss')79        plt.ylabel('loss')80        plt.xlabel('epoch')81        plt.legend(['train', 'test'], loc='upper left')82        plt.savefig('lossplot.png')83        return 'lossplot.png',accuracy84    85    86    87iface = gr.Interface(88    malware_detection_DL, [gr.inputs.Dropdown(["Accuracy","Loss"], label="Result Type"),89                                     gr.inputs.Dropdown(["malicious_flows.csv"], label = "Malicious traffic in .csv"),90                           gr.inputs.Dropdown(["sample_benign_flows.csv"], label="Benign Traffic in .csv")91                          ],["image","text"], theme="grass"92    93    94)95 96iface.launch(enable_queue = True)97