SlideShare a Scribd company logo
1 of 9
Download to read offline
Hello, I hope you are doing well,
I am doing my project, which is Ransomware attack detection using Deep learning CNNs
I got a result of 0.93, which is not good enough, I have tried to improve my accuracy, but I gave
up. Could you modify the code feature selection or pre-processing to get a higher result? Even
for that result, I have to wait a long time to get it because I increased the epoch, and could you
explain the added part?
import os
import numpy as np
import pandas as pd
import keras
import tensorflow as tf
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
from keras.preprocessing.image import ImageDataGenerator #, 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, Dropout, Flatten, Dense, Activation,
BatchNormalization
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
print(os.listdir("D:RansomSecondApproachRansomware_Detection_using
_CNNMixImages"))
# Define Constants
FAST_RUN = False
IMAGE_WIDTH=128 # maybe 256
IMAGE_HEIGHT=128 # 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()
# See sample image
# sample = random.choice(filenames)
# image = load_img("D:Ransomware_Detection_using _CNNMixImages"+sample)
# plt.imshow(image)
# in collab it will work df['category'].value_counts().plot.bar()
# Build Model
#====================================================================
===========================================
# Testing
model = Sequential()
model.add(Conv2D(32, (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(64, (3, 3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(256, (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='rmsprop', metrics=['accuracy'])
model.summary()
# 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)
##plot in collab
###train_df['category'].value_counts().plot.bar()
###validate_df['category'].value_counts().plot.bar()
total_train = train_df.shape[0]
total_validate = validate_df.shape[0]
batch_size = 512
# Traning Generator
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
)
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 _CNNMixImagess",
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'
)
epochs = 30 # 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,
callbacks=callbacks
)
# Save Model
model.save_weights("model.h5")
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(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({ 'malware': 1, 'bengin': 0 })
# 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

Similar to Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf

Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfactexerode
 
Need helping adding to the code below to plot the images from the firs.pdf
Need helping adding to the code below to plot the images from the firs.pdfNeed helping adding to the code below to plot the images from the firs.pdf
Need helping adding to the code below to plot the images from the firs.pdfactexerode
 
Unsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at ScaleUnsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at ScaleAaron (Ari) Bornstein
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......hugo lu
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnnDebarko De
 
집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링Kwang Woo NAM
 
Training course lect2
Training course lect2Training course lect2
Training course lect2Noor Dhiya
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Competition 1 (blog 1)
Competition 1 (blog 1)Competition 1 (blog 1)
Competition 1 (blog 1)TarunPaparaju
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxTseChris
 
Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxLukeQVdGrantg
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret packageVivian S. Zhang
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedEspeo Software
 
Learning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and KaggleLearning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and KaggleYvonne K. Matos
 
GANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfGANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfVivekanandaGN1
 

Similar to Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf (20)

Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
 
Need helping adding to the code below to plot the images from the firs.pdf
Need helping adding to the code below to plot the images from the firs.pdfNeed helping adding to the code below to plot the images from the firs.pdf
Need helping adding to the code below to plot the images from the firs.pdf
 
Unsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at ScaleUnsupervised Aspect Based Sentiment Analysis at Scale
Unsupervised Aspect Based Sentiment Analysis at Scale
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnn
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
 
집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링
 
Training course lect2
Training course lect2Training course lect2
Training course lect2
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Competition 1 (blog 1)
Competition 1 (blog 1)Competition 1 (blog 1)
Competition 1 (blog 1)
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docx
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret package
 
Celery
CeleryCelery
Celery
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to Advanced
 
Learning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and KaggleLearning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and Kaggle
 
GANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfGANS Project for Image idetification.pdf
GANS Project for Image idetification.pdf
 

More from Ian0J2Bondo

Results and Observations Growth on slant- Describe the growth on your (1).pdf
Results and Observations Growth on slant- Describe the growth on your (1).pdfResults and Observations Growth on slant- Describe the growth on your (1).pdf
Results and Observations Growth on slant- Describe the growth on your (1).pdfIan0J2Bondo
 
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdf
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdfRestaurateur Denny Valentine is evaluating two sites- Raymondville and.pdf
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdfIan0J2Bondo
 
Resource governance means that a container has access only to a specif.pdf
Resource governance means that a container has access only to a specif.pdfResource governance means that a container has access only to a specif.pdf
Resource governance means that a container has access only to a specif.pdfIan0J2Bondo
 
Respond to the following in a minimum of 175 words- Analyze the risks.pdf
Respond to the following in a minimum of 175 words-  Analyze the risks.pdfRespond to the following in a minimum of 175 words-  Analyze the risks.pdf
Respond to the following in a minimum of 175 words- Analyze the risks.pdfIan0J2Bondo
 
Researchers investigate the association between the rate of hospitalza.pdf
Researchers investigate the association between the rate of hospitalza.pdfResearchers investigate the association between the rate of hospitalza.pdf
Researchers investigate the association between the rate of hospitalza.pdfIan0J2Bondo
 
Researchers found that a person in a particular country spent an avera.pdf
Researchers found that a person in a particular country spent an avera.pdfResearchers found that a person in a particular country spent an avera.pdf
Researchers found that a person in a particular country spent an avera.pdfIan0J2Bondo
 
Research the relationship between the cardiac vector and the ECG signa.pdf
Research the relationship between the cardiac vector and the ECG signa.pdfResearch the relationship between the cardiac vector and the ECG signa.pdf
Research the relationship between the cardiac vector and the ECG signa.pdfIan0J2Bondo
 
Research Subject Datacenters have evolved over time to handle differen.pdf
Research Subject Datacenters have evolved over time to handle differen.pdfResearch Subject Datacenters have evolved over time to handle differen.pdf
Research Subject Datacenters have evolved over time to handle differen.pdfIan0J2Bondo
 
Research the USA and Canadian responses to COVID-19 and complete the f.pdf
Research the USA and Canadian responses to COVID-19 and complete the f.pdfResearch the USA and Canadian responses to COVID-19 and complete the f.pdf
Research the USA and Canadian responses to COVID-19 and complete the f.pdfIan0J2Bondo
 
Research Paper You will select a topic pertinent to the course subject.pdf
Research Paper You will select a topic pertinent to the course subject.pdfResearch Paper You will select a topic pertinent to the course subject.pdf
Research Paper You will select a topic pertinent to the course subject.pdfIan0J2Bondo
 
Research and discuss 4 other mammalian reflexes other than the mention.pdf
Research and discuss 4 other mammalian reflexes other than the mention.pdfResearch and discuss 4 other mammalian reflexes other than the mention.pdf
Research and discuss 4 other mammalian reflexes other than the mention.pdfIan0J2Bondo
 
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdf
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdfRequirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdf
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdfIan0J2Bondo
 
Requirement 1- Prepare the April income statement under absorption cos.pdf
Requirement 1- Prepare the April income statement under absorption cos.pdfRequirement 1- Prepare the April income statement under absorption cos.pdf
Requirement 1- Prepare the April income statement under absorption cos.pdfIan0J2Bondo
 
Required- a) What amount of gain or loss does Ramona realize on the fo.pdf
Required- a) What amount of gain or loss does Ramona realize on the fo.pdfRequired- a) What amount of gain or loss does Ramona realize on the fo.pdf
Required- a) What amount of gain or loss does Ramona realize on the fo.pdfIan0J2Bondo
 
Required information Use the following information for the Quick Studi.pdf
Required information Use the following information for the Quick Studi.pdfRequired information Use the following information for the Quick Studi.pdf
Required information Use the following information for the Quick Studi.pdfIan0J2Bondo
 
Required information Use the followlng lnformetlon for the Exerclses b.pdf
Required information Use the followlng lnformetlon for the Exerclses b.pdfRequired information Use the followlng lnformetlon for the Exerclses b.pdf
Required information Use the followlng lnformetlon for the Exerclses b.pdfIan0J2Bondo
 
Required information The lifetime of a lightbulb in a certain applicat (1).pdf
Required information The lifetime of a lightbulb in a certain applicat (1).pdfRequired information The lifetime of a lightbulb in a certain applicat (1).pdf
Required information The lifetime of a lightbulb in a certain applicat (1).pdfIan0J2Bondo
 
Required information Shown below are the maps of a series of ril delet.pdf
Required information Shown below are the maps of a series of ril delet.pdfRequired information Shown below are the maps of a series of ril delet.pdf
Required information Shown below are the maps of a series of ril delet.pdfIan0J2Bondo
 
Required information Reporting Amounts on the Four Basic Financial Sta.pdf
Required information Reporting Amounts on the Four Basic Financial Sta.pdfRequired information Reporting Amounts on the Four Basic Financial Sta.pdf
Required information Reporting Amounts on the Four Basic Financial Sta.pdfIan0J2Bondo
 
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdf
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdfRequired information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdf
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdfIan0J2Bondo
 

More from Ian0J2Bondo (20)

Results and Observations Growth on slant- Describe the growth on your (1).pdf
Results and Observations Growth on slant- Describe the growth on your (1).pdfResults and Observations Growth on slant- Describe the growth on your (1).pdf
Results and Observations Growth on slant- Describe the growth on your (1).pdf
 
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdf
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdfRestaurateur Denny Valentine is evaluating two sites- Raymondville and.pdf
Restaurateur Denny Valentine is evaluating two sites- Raymondville and.pdf
 
Resource governance means that a container has access only to a specif.pdf
Resource governance means that a container has access only to a specif.pdfResource governance means that a container has access only to a specif.pdf
Resource governance means that a container has access only to a specif.pdf
 
Respond to the following in a minimum of 175 words- Analyze the risks.pdf
Respond to the following in a minimum of 175 words-  Analyze the risks.pdfRespond to the following in a minimum of 175 words-  Analyze the risks.pdf
Respond to the following in a minimum of 175 words- Analyze the risks.pdf
 
Researchers investigate the association between the rate of hospitalza.pdf
Researchers investigate the association between the rate of hospitalza.pdfResearchers investigate the association between the rate of hospitalza.pdf
Researchers investigate the association between the rate of hospitalza.pdf
 
Researchers found that a person in a particular country spent an avera.pdf
Researchers found that a person in a particular country spent an avera.pdfResearchers found that a person in a particular country spent an avera.pdf
Researchers found that a person in a particular country spent an avera.pdf
 
Research the relationship between the cardiac vector and the ECG signa.pdf
Research the relationship between the cardiac vector and the ECG signa.pdfResearch the relationship between the cardiac vector and the ECG signa.pdf
Research the relationship between the cardiac vector and the ECG signa.pdf
 
Research Subject Datacenters have evolved over time to handle differen.pdf
Research Subject Datacenters have evolved over time to handle differen.pdfResearch Subject Datacenters have evolved over time to handle differen.pdf
Research Subject Datacenters have evolved over time to handle differen.pdf
 
Research the USA and Canadian responses to COVID-19 and complete the f.pdf
Research the USA and Canadian responses to COVID-19 and complete the f.pdfResearch the USA and Canadian responses to COVID-19 and complete the f.pdf
Research the USA and Canadian responses to COVID-19 and complete the f.pdf
 
Research Paper You will select a topic pertinent to the course subject.pdf
Research Paper You will select a topic pertinent to the course subject.pdfResearch Paper You will select a topic pertinent to the course subject.pdf
Research Paper You will select a topic pertinent to the course subject.pdf
 
Research and discuss 4 other mammalian reflexes other than the mention.pdf
Research and discuss 4 other mammalian reflexes other than the mention.pdfResearch and discuss 4 other mammalian reflexes other than the mention.pdf
Research and discuss 4 other mammalian reflexes other than the mention.pdf
 
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdf
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdfRequirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdf
Requirements- 1 Post the unadjusted balances of Daily Driver Inc- to t.pdf
 
Requirement 1- Prepare the April income statement under absorption cos.pdf
Requirement 1- Prepare the April income statement under absorption cos.pdfRequirement 1- Prepare the April income statement under absorption cos.pdf
Requirement 1- Prepare the April income statement under absorption cos.pdf
 
Required- a) What amount of gain or loss does Ramona realize on the fo.pdf
Required- a) What amount of gain or loss does Ramona realize on the fo.pdfRequired- a) What amount of gain or loss does Ramona realize on the fo.pdf
Required- a) What amount of gain or loss does Ramona realize on the fo.pdf
 
Required information Use the following information for the Quick Studi.pdf
Required information Use the following information for the Quick Studi.pdfRequired information Use the following information for the Quick Studi.pdf
Required information Use the following information for the Quick Studi.pdf
 
Required information Use the followlng lnformetlon for the Exerclses b.pdf
Required information Use the followlng lnformetlon for the Exerclses b.pdfRequired information Use the followlng lnformetlon for the Exerclses b.pdf
Required information Use the followlng lnformetlon for the Exerclses b.pdf
 
Required information The lifetime of a lightbulb in a certain applicat (1).pdf
Required information The lifetime of a lightbulb in a certain applicat (1).pdfRequired information The lifetime of a lightbulb in a certain applicat (1).pdf
Required information The lifetime of a lightbulb in a certain applicat (1).pdf
 
Required information Shown below are the maps of a series of ril delet.pdf
Required information Shown below are the maps of a series of ril delet.pdfRequired information Shown below are the maps of a series of ril delet.pdf
Required information Shown below are the maps of a series of ril delet.pdf
 
Required information Reporting Amounts on the Four Basic Financial Sta.pdf
Required information Reporting Amounts on the Four Basic Financial Sta.pdfRequired information Reporting Amounts on the Four Basic Financial Sta.pdf
Required information Reporting Amounts on the Four Basic Financial Sta.pdf
 
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdf
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdfRequired information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdf
Required information E6-17 (Algo) Analyzing Gross Profit Percentage on.pdf
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfcupulin
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 

Recently uploaded (20)

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 

Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf

  • 1. Hello, I hope you are doing well, I am doing my project, which is Ransomware attack detection using Deep learning CNNs I got a result of 0.93, which is not good enough, I have tried to improve my accuracy, but I gave up. Could you modify the code feature selection or pre-processing to get a higher result? Even for that result, I have to wait a long time to get it because I increased the epoch, and could you explain the added part? import os import numpy as np import pandas as pd import keras import tensorflow as tf # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 # os.environ['CUDA_VISIBLE_DEVICES'] = '-1' from keras.preprocessing.image import ImageDataGenerator #, 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, Dropout, Flatten, Dense, Activation, BatchNormalization from keras.callbacks import EarlyStopping, ReduceLROnPlateau print(os.listdir("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages")) # Define Constants FAST_RUN = False
  • 2. IMAGE_WIDTH=128 # maybe 256 IMAGE_HEIGHT=128 # 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())
  • 3. # in collab it will work df['category'].value_counts().plot.bar() # See sample image # sample = random.choice(filenames) # image = load_img("D:Ransomware_Detection_using _CNNMixImages"+sample) # plt.imshow(image) # in collab it will work df['category'].value_counts().plot.bar() # Build Model #==================================================================== =========================================== # Testing model = Sequential() model.add(Conv2D(32, (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(64, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25))
  • 4. model.add(Conv2D(256, (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='rmsprop', metrics=['accuracy']) model.summary() # 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
  • 5. 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) ##plot in collab ###train_df['category'].value_counts().plot.bar() ###validate_df['category'].value_counts().plot.bar() total_train = train_df.shape[0] total_validate = validate_df.shape[0] batch_size = 512 # Traning Generator 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 ) train_generator = train_datagen.flow_from_dataframe( train_df, "D:RansomSecondApproachRansomware_Detection_using _CNNMixImages",
  • 6. 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 _CNNMixImagess", 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",
  • 7. x_col='filename', y_col='category', target_size=IMAGE_SIZE, class_mode='categorical' ) epochs = 30 # 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, callbacks=callbacks ) # Save Model model.save_weights("model.h5") test_filenames = os.listdir("D:RansomSecondApproachRansomware_Detection_using _CNNMixImages") test_df = pd.DataFrame({ 'filename': test_filenames }) nb_samples = test_df.shape[0]
  • 8. # 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(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({ 'malware': 1, 'bengin': 0 }) # Submission submission_df = test_df.copy() submission_df['id'] = submission_df['filename'].str.split('.').str[0]
  • 9. submission_df['label'] = submission_df['category'] submission_df.drop(['filename', 'category'], axis=1, inplace=True) submission_df.to_csv('submission.csv', index=False)