SlideShare a Scribd company logo
I want you to add the output of the F1 score, Precision, ROC AUC, and Cohen kappa to fit in the
code below, and please consider the code provided.
import os
import numpy as np
import pandas as pd
import keras
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import load_img
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import random
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, MaxPool2D , Dropout, Flatten, Dense,
Activation, BatchNormalization
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from sklearn.utils import class_weight
import keras,os
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D , Flatten
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score,
cohen_kappa_score, roc_auc_score
print(os.listdir("D:RansomSecondApproachRansomware_Detection_using
_CNNMixImages"))
# Define Constants
FAST_RUN = False
IMAGE_WIDTH=256 # 150 accept maybe 256
IMAGE_HEIGHT=256 # maybe 256
IMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)
IMAGE_CHANNELS=3 # maybe not need
physical_devices = tf.config.experimental.list_physical_devices('GPU')
print(physical_devices)
if physical_devices:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
# Prepare Traning Data
filenames = os.listdir("D:RansomSecondApproachRansomware_Detection_using
_CNNMixImages")
categories = []
for filename in filenames:
category = filename.split('l')[0]
if category == 'image_benign_':
categories.append(0)
else:
categories.append(1)
df = pd.DataFrame({
'filename': filenames,
'category': categories
})
print(df.head())
print(df.tail())
# in collab it will work
df['category'].value_counts().plot.bar()
model = Sequential()
model.add(Conv2D(16, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH,
IMAGE_HEIGHT, IMAGE_CHANNELS)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Callbacks
## Early Stop To prevent over fitting we will stop the learning after 10 epochs and val_loss value
not decreased
earlystop = EarlyStopping(patience=10)
# Learning Rate Reduction
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=2,
verbose=1,
factor=0.5,
min_lr=0.00001)
callbacks = [earlystop, learning_rate_reduction]
#Prepare data
df["category"] = df["category"].replace({0: 'benign', 1: 'malware'})
train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)
train_df = train_df.reset_index(drop=True)
validate_df = validate_df.reset_index(drop=True)
total_train = train_df.shape[0]
total_validate = validate_df.shape[0]
batch_size= 15 # defualt 15
# Traning Generator
# Defualt
train_datagen = ImageDataGenerator(
rotation_range=15,
rescale=1./255,
shear_range=0.1,
zoom_range=0.2,
horizontal_flip=True,
width_shift_range=0.1,
height_shift_range=0.1
)
###############################################
# Augmenting the training data
train_generator = train_datagen.flow_from_dataframe(
train_df,
"D:RansomSecondApproachRansomware_Detection_using _CNNMixImages",
x_col='filename',
y_col='category',
target_size=IMAGE_SIZE,
class_mode='categorical',
batch_size=batch_size
)
# Validation Generator
validation_datagen = ImageDataGenerator(rescale=1./255)
validation_generator = validation_datagen.flow_from_dataframe(
validate_df,
"D:RansomSecondApproachRansomware_Detection_using _CNNMixImages",
x_col='filename',
y_col='category',
target_size=IMAGE_SIZE,
class_mode='categorical',
batch_size=batch_size
)
# See how our generator work
example_df = train_df.sample(n=1).reset_index(drop=True)
example_generator = train_datagen.flow_from_dataframe(
example_df,
"D:RansomSecondApproachRansomware_Detection_using _CNNMixImages",
x_col='filename',
y_col='category',
target_size=IMAGE_SIZE,
class_mode='categorical'
)
# in collab it will work
plt.figure(figsize=(12, 12))
for i in range(0, 15):
plt.subplot(5, 3, i+1)
for X_batch, Y_batch in example_generator:
image = X_batch[0]
plt.imshow(image)
break
plt.tight_layout()
plt.show()
# compile
epochs = 1 # if FAST_RUN else 50
history = model.fit(
train_generator,
epochs=epochs,
validation_data=validation_generator,
validation_steps=total_validate//batch_size,
steps_per_epoch=total_train//batch_size,
# class_weight=class_weights, # add
# shuffle=True,
callbacks=callbacks
)
model.save_weights("model.h5")
# Virtualize Training
##in collab
# fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))
# ax1.plot(history.history['loss'], color='b', label="Training loss")
# ax1.plot(history.history['val_loss'], color='r', label="validation loss")
# ax1.set_xticks(np.arange(1, epochs, 1))
# ax1.set_yticks(np.arange(0, 1, 0.1))
# ax2.plot(history.history['acc'], color='b', label="Training accuracy")
# ax2.plot(history.history['val_acc'], color='r',label="Validation accuracy")
# ax2.set_xticks(np.arange(1, epochs, 1))
# legend = plt.legend(loc='best', shadow=True)
# plt.tight_layout()
# plt.show()
# Prepare Testing Data
test_filenames = os.listdir("D:RansomSecondApproachRansomware_Detection_using
_CNNMixImages")
test_df = pd.DataFrame({
'filename': test_filenames
})
nb_samples = test_df.shape[0]
# Create Testing Generator
# output Found 12500 images in kaggle.
test_gen = ImageDataGenerator(rescale=1./255)
test_generator = test_gen.flow_from_dataframe(
test_df,
"D:RansomSecondApproachRansomware_Detection_using _CNNMixImages",
x_col='filename',
y_col=None,
class_mode=None,
target_size=IMAGE_SIZE,
batch_size=batch_size,
shuffle=False
)
# Predict
predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))
test_df['category'] = np.argmax(predict, axis=-1)
label_map = dict((v,k) for k,v in train_generator.class_indices.items())
test_df['category'] = test_df['category'].replace(label_map)
test_df['category'] = test_df['category'].replace({ 0: 'benign', 1: 'malware' })
# Virtaulize Result
# Compute the average training and validation accuracy
avg_train_acc = np.mean(history.history['accuracy'])
avg_val_acc = np.mean(history.history['val_accuracy'])
# Print the average training and validation accuracy
print("Average training accuracy:", avg_train_acc)
print("Average validation accuracy:", avg_val_acc)
#in collab
test_df['category'].value_counts().plot.bar()
# See predicted result with images
# in collab
sample_test = test_df.head(18)
sample_test.head()
plt.figure(figsize=(12, 24))
for index, row in sample_test.iterrows():
filename = row['filename']
category = row['category']
img = load_img("D:RansomSecondApproachRansomware_Detection_using
_CNNMixImages" +filename, target_size=IMAGE_SIZE)
plt.subplot(6, 3, index+1)
plt.imshow(img)
plt.xlabel(filename + '(' + "{}".format(category) + ')' )
plt.tight_layout()
plt.show()
# Submission
submission_df = test_df.copy()
submission_df['id'] = submission_df['filename'].str.split('.').str[0]
submission_df['label'] = submission_df['category']
submission_df.drop(['filename', 'category'], axis=1, inplace=True)
submission_df.to_csv('submission.csv', index=False)

More Related Content

PDF
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
PDF
I have tried running this code below- and it is working- but the accur.pdf
PDF
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
DOCX
Python program to build deep learning algorithm using a CNNs model to.docx
PDF
Using the code below- I need help with the following 3 things- 1) Writ.pdf
PDF
A Tour of Tensorflow's APIs
PDF
Can someone please explain what the code below is doing and comment on.pdf
PDF
GANS Project for Image idetification.pdf
I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf
I have tried running this code below- and it is working- but the accur.pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Python program to build deep learning algorithm using a CNNs model to.docx
Using the code below- I need help with the following 3 things- 1) Writ.pdf
A Tour of Tensorflow's APIs
Can someone please explain what the code below is doing and comment on.pdf
GANS Project for Image idetification.pdf

Similar to I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf (20)

PDF
Power ai tensorflowworkloadtutorial-20171117
PDF
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
PDF
OpenPOWER Workshop in Silicon Valley
PDF
Keras and TensorFlow
PPTX
Explanation on Tensorflow example -Deep mnist for expert
PDF
Assignment 6.1.pdf
PPTX
Learning Predictive Modeling with TSA and Kaggle
DOCX
CSCE509–Spring2019Assignment3updated01May19DU.docx
PDF
Assignment 5.2.pdf
PDF
Assignment 6.2a.pdf
DOCX
inception.docx
PPTX
AI_ML_WORKSHOP_plant_disease_detection.pptx
PPTX
AI_ML_WORKSHOP_project_on_plant_disease_detection.pptx
PDF
AIML4 CNN lab256 1hr (111-1).pdf
PDF
Structure Unstructured Data
PDF
TensorFlow and Keras: An Overview
DOCX
Need help filling out the missing sections of this code- the sections.docx
PDF
Need helping adding to the code below to plot the images from the firs.pdf
PPTX
TensorFlow in Practice
PDF
Neural networks using tensor flow in amazon deep learning server
Power ai tensorflowworkloadtutorial-20171117
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
OpenPOWER Workshop in Silicon Valley
Keras and TensorFlow
Explanation on Tensorflow example -Deep mnist for expert
Assignment 6.1.pdf
Learning Predictive Modeling with TSA and Kaggle
CSCE509–Spring2019Assignment3updated01May19DU.docx
Assignment 5.2.pdf
Assignment 6.2a.pdf
inception.docx
AI_ML_WORKSHOP_plant_disease_detection.pptx
AI_ML_WORKSHOP_project_on_plant_disease_detection.pptx
AIML4 CNN lab256 1hr (111-1).pdf
Structure Unstructured Data
TensorFlow and Keras: An Overview
Need help filling out the missing sections of this code- the sections.docx
Need helping adding to the code below to plot the images from the firs.pdf
TensorFlow in Practice
Neural networks using tensor flow in amazon deep learning server
Ad

More from GordonF2XPatersonh (20)

PDF
import java-lang-Comparable- -- new Main-String-() public class Main-.pdf
PDF
In 2022- Jacques paid the following interest- Interest on home mortgag.pdf
PDF
In 2020- the world was made aware of the highly contagious and occasio.pdf
PDF
Implement an extended version of the Caesar cipher that users the char.pdf
PDF
Implement FIFO queue using two stacks in Python- Methods should have O.pdf
PDF
import java-util-ArrayList- public class Bus { private String na.pdf
PDF
Imagine a natural area near your hometown that has been identified as.pdf
PDF
If you wish to estimate a population mean with a sampling distribution.pdf
PDF
igate Search Project Run Window Help D eclipse-worksoace - Names javar.pdf
PDF
If you have a dataset with n-42- mean is 50- the standard deviation is.pdf
PDF
If you combine cooking oil (a lipid) with water in a measuring cup- th.pdf
PDF
If X has a binomial random variable with probability distribution f(x).pdf
PDF
If we look at the diagram below we notice that there are soveral chara.pdf
PDF
If total assets decrease- then which of the following statements is tr.pdf
PDF
If two different accountants were to estimate the percentage of custom.pdf
PDF
If the radius of the Earth were to increase by a factor of 4 while its.pdf
PDF
If the government suddenly decided to include the non-civilian employe.pdf
PDF
If the Earth's P-wave velocities were faster than they actually are- t.pdf
PDF
If the Earth was made-up entirely of crustal rocks- then what would th.pdf
PDF
If the anhydrous compound (AC) in the preceding problem has a molar ma.pdf
import java-lang-Comparable- -- new Main-String-() public class Main-.pdf
In 2022- Jacques paid the following interest- Interest on home mortgag.pdf
In 2020- the world was made aware of the highly contagious and occasio.pdf
Implement an extended version of the Caesar cipher that users the char.pdf
Implement FIFO queue using two stacks in Python- Methods should have O.pdf
import java-util-ArrayList- public class Bus { private String na.pdf
Imagine a natural area near your hometown that has been identified as.pdf
If you wish to estimate a population mean with a sampling distribution.pdf
igate Search Project Run Window Help D eclipse-worksoace - Names javar.pdf
If you have a dataset with n-42- mean is 50- the standard deviation is.pdf
If you combine cooking oil (a lipid) with water in a measuring cup- th.pdf
If X has a binomial random variable with probability distribution f(x).pdf
If we look at the diagram below we notice that there are soveral chara.pdf
If total assets decrease- then which of the following statements is tr.pdf
If two different accountants were to estimate the percentage of custom.pdf
If the radius of the Earth were to increase by a factor of 4 while its.pdf
If the government suddenly decided to include the non-civilian employe.pdf
If the Earth's P-wave velocities were faster than they actually are- t.pdf
If the Earth was made-up entirely of crustal rocks- then what would th.pdf
If the anhydrous compound (AC) in the preceding problem has a molar ma.pdf
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Empowerment Technology for Senior High School Guide
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Indian roads congress 037 - 2012 Flexible pavement
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
RMMM.pdf make it easy to upload and study
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
IGGE1 Understanding the Self1234567891011
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
Final Presentation General Medicine 03-08-2024.pptx
Empowerment Technology for Senior High School Guide
Computing-Curriculum for Schools in Ghana
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Indian roads congress 037 - 2012 Flexible pavement
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
202450812 BayCHI UCSC-SV 20250812 v17.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
RMMM.pdf make it easy to upload and study
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
LDMMIA Reiki Yoga Finals Review Spring Summer
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
IGGE1 Understanding the Self1234567891011
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Orientation - ARALprogram of Deped to the Parents.pptx

I want you to add the output of the F1 score- Precision- ROC AUC- and.pdf

  • 1. I want you to add the output of the F1 score, Precision, ROC AUC, and Cohen kappa to fit in the code below, and please consider the code provided. import os import numpy as np import pandas as pd import keras import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator from keras.utils import load_img from keras.utils import to_categorical from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import random from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, MaxPool2D , Dropout, Flatten, Dense, Activation, BatchNormalization from keras.callbacks import EarlyStopping, ReduceLROnPlateau from sklearn.utils import class_weight import keras,os from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPool2D , Flatten from keras.preprocessing.image import ImageDataGenerator import numpy as np from keras.optimizers import Adam
  • 2. from keras.callbacks import ModelCheckpoint, EarlyStopping from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, cohen_kappa_score, roc_auc_score print(os.listdir("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages")) # Define Constants FAST_RUN = False IMAGE_WIDTH=256 # 150 accept maybe 256 IMAGE_HEIGHT=256 # maybe 256 IMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT) IMAGE_CHANNELS=3 # maybe not need physical_devices = tf.config.experimental.list_physical_devices('GPU') print(physical_devices) if physical_devices: tf.config.experimental.set_memory_growth(physical_devices[0], True) # Prepare Traning Data filenames = os.listdir("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages") categories = [] for filename in filenames: category = filename.split('l')[0] if category == 'image_benign_': categories.append(0) else: categories.append(1)
  • 3. df = pd.DataFrame({ 'filename': filenames, 'category': categories }) print(df.head()) print(df.tail()) # in collab it will work df['category'].value_counts().plot.bar() model = Sequential() model.add(Conv2D(16, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS))) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation='relu'))
  • 4. model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # Callbacks ## Early Stop To prevent over fitting we will stop the learning after 10 epochs and val_loss value not decreased earlystop = EarlyStopping(patience=10) # Learning Rate Reduction learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=2, verbose=1, factor=0.5, min_lr=0.00001) callbacks = [earlystop, learning_rate_reduction] #Prepare data df["category"] = df["category"].replace({0: 'benign', 1: 'malware'}) train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42) train_df = train_df.reset_index(drop=True) validate_df = validate_df.reset_index(drop=True) total_train = train_df.shape[0] total_validate = validate_df.shape[0] batch_size= 15 # defualt 15 # Traning Generator
  • 5. # Defualt train_datagen = ImageDataGenerator( rotation_range=15, rescale=1./255, shear_range=0.1, zoom_range=0.2, horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1 ) ############################################### # Augmenting the training data train_generator = train_datagen.flow_from_dataframe( train_df, "D:RansomSecondApproachRansomware_Detection_using _CNNMixImages", x_col='filename', y_col='category', target_size=IMAGE_SIZE, class_mode='categorical', batch_size=batch_size ) # Validation Generator validation_datagen = ImageDataGenerator(rescale=1./255)
  • 6. validation_generator = validation_datagen.flow_from_dataframe( validate_df, "D:RansomSecondApproachRansomware_Detection_using _CNNMixImages", x_col='filename', y_col='category', target_size=IMAGE_SIZE, class_mode='categorical', batch_size=batch_size ) # See how our generator work example_df = train_df.sample(n=1).reset_index(drop=True) example_generator = train_datagen.flow_from_dataframe( example_df, "D:RansomSecondApproachRansomware_Detection_using _CNNMixImages", x_col='filename', y_col='category', target_size=IMAGE_SIZE, class_mode='categorical' ) # in collab it will work plt.figure(figsize=(12, 12)) for i in range(0, 15): plt.subplot(5, 3, i+1)
  • 7. for X_batch, Y_batch in example_generator: image = X_batch[0] plt.imshow(image) break plt.tight_layout() plt.show() # compile epochs = 1 # if FAST_RUN else 50 history = model.fit( train_generator, epochs=epochs, validation_data=validation_generator, validation_steps=total_validate//batch_size, steps_per_epoch=total_train//batch_size, # class_weight=class_weights, # add # shuffle=True, callbacks=callbacks ) model.save_weights("model.h5") # Virtualize Training ##in collab # fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12)) # ax1.plot(history.history['loss'], color='b', label="Training loss")
  • 8. # ax1.plot(history.history['val_loss'], color='r', label="validation loss") # ax1.set_xticks(np.arange(1, epochs, 1)) # ax1.set_yticks(np.arange(0, 1, 0.1)) # ax2.plot(history.history['acc'], color='b', label="Training accuracy") # ax2.plot(history.history['val_acc'], color='r',label="Validation accuracy") # ax2.set_xticks(np.arange(1, epochs, 1)) # legend = plt.legend(loc='best', shadow=True) # plt.tight_layout() # plt.show() # Prepare Testing Data test_filenames = os.listdir("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages") test_df = pd.DataFrame({ 'filename': test_filenames }) nb_samples = test_df.shape[0] # Create Testing Generator # output Found 12500 images in kaggle. test_gen = ImageDataGenerator(rescale=1./255) test_generator = test_gen.flow_from_dataframe( test_df, "D:RansomSecondApproachRansomware_Detection_using _CNNMixImages", x_col='filename', y_col=None,
  • 9. class_mode=None, target_size=IMAGE_SIZE, batch_size=batch_size, shuffle=False ) # Predict predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size)) test_df['category'] = np.argmax(predict, axis=-1) label_map = dict((v,k) for k,v in train_generator.class_indices.items()) test_df['category'] = test_df['category'].replace(label_map) test_df['category'] = test_df['category'].replace({ 0: 'benign', 1: 'malware' }) # Virtaulize Result # Compute the average training and validation accuracy avg_train_acc = np.mean(history.history['accuracy']) avg_val_acc = np.mean(history.history['val_accuracy']) # Print the average training and validation accuracy print("Average training accuracy:", avg_train_acc) print("Average validation accuracy:", avg_val_acc) #in collab test_df['category'].value_counts().plot.bar() # See predicted result with images # in collab sample_test = test_df.head(18)
  • 10. sample_test.head() plt.figure(figsize=(12, 24)) for index, row in sample_test.iterrows(): filename = row['filename'] category = row['category'] img = load_img("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages" +filename, target_size=IMAGE_SIZE) plt.subplot(6, 3, index+1) plt.imshow(img) plt.xlabel(filename + '(' + "{}".format(category) + ')' ) plt.tight_layout() plt.show() # Submission submission_df = test_df.copy() submission_df['id'] = submission_df['filename'].str.split('.').str[0] submission_df['label'] = submission_df['category'] submission_df.drop(['filename', 'category'], axis=1, inplace=True) submission_df.to_csv('submission.csv', index=False)