-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCNN_Malware_Train_Test.py
158 lines (125 loc) · 6.16 KB
/
CNN_Malware_Train_Test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
from inspect import ArgSpec
import torch
import torch.nn as nn
import numpy as np
import torch.nn as nn
import torch.optim as optim
from data_loaders import *
from CNN_Models import *
from metrics import *
import matplotlib.pyplot as plt
import argparse
def train(model_name, batch_size, dropout, epochs, image_size, learning_rate):
device = get_device()
if(model_name == "Model_One"):
network = MalCnnOne(dropout, image_size).to(device)
elif(model_name == "Model_Two"):
network = MalCnnTwo(dropout, image_size).to(device)
optimizer = optim.Adam(network.parameters(), lr=learning_rate, weight_decay=5e-4)
criterion = nn.CrossEntropyLoss()
train_loader, valid_loader = get_image_data_train_val_loaders(image_size, batch_size)
valid_loss_min = np.Inf # track change in validation loss
for epoch in range(epochs):
train_total_loss = 0.0
train_loss=0.0
###################
# train the model #
###################
network.train()
for images, labels in train_loader:
images, labels = to_device(images, device), to_device(labels, device)
optimizer.zero_grad()
output = network(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
######################
# validate the model #
######################
valid_total_loss = 0.0
valid_loss = 0.0
network.eval()
for images, labels in valid_loader:
images,labels = to_device(images, device), to_device(labels, device)
output = network(images)
loss = criterion(output, labels)
valid_loss += loss.item()
train_total_loss = train_loss/len(train_loader.dataset)
valid_total_loss = valid_loss/len(valid_loader.dataset)
with open("train_output/train_losses_{}.txt".format(model_name), "a") as file:
file.write(str(train_total_loss)+","+str(valid_total_loss)+"\n")
# print training/validation statistics
print("Epoch: {}/{} \t Average Training Loss: {:.8f}, Average Validation Loss: {:.8f}".format(epoch + 1, epochs, train_total_loss, valid_total_loss))
# save model if validation loss has decreased
if valid_loss <= valid_loss_min:
print('Validation loss decreased ({:.8f} --> {:.8f}). Saving model ...'.format(valid_loss_min, valid_loss))
torch.save(network.state_dict(), 'train_output/Mal_CNN_Detect_{}.pt'.format(model_name))
valid_loss_min = valid_loss
train_val_loss_plot(model_name, epochs)
print("==================== Trained Model Saved ====================")
def load_model(model_name):
model=None
if model_name == "Model_One":
model = MalCnnOne()
model.load_state_dict(torch.load('train_output/Mal_CNN_Detect_Model_One.pt'))
else:
model = MalCnnTwo()
model.load_state_dict(torch.load('train_output/Mal_CNN_Detect_Model_Two.pt'))
return model
def test_model(image_size, model_name):
devices = get_device()
accuracy = 0.0
test_accuracy=[]
test_loss=0.0
test_loader = get_image_data_test_loader(image_size, 32)
criterion = nn.CrossEntropyLoss()
model = load_model(model_name).to(devices)
with torch.no_grad():
model.eval()
for images, labels in test_loader:
accuracy_vals = 0.0
images,labels = to_device(images, devices), to_device(labels, devices)
output = model(images)
loss = criterion(output, labels)
test_loss += loss.item()
ps = torch.exp(output)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor))
accuracy_vals = ((accuracy/len(test_loader))*100)
test_accuracy.append(accuracy_vals)
print("Test Accuracy: {:.8f}".format(accuracy_vals))
test_accuracy_plot(test_accuracy,model_name)
calc_confusion_matrix(test_loader, devices, model, model_name)
def get_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def to_device(data, device):
return data.to(device, non_blocking=True)
def main(task, model_name):
if task=="train":
if model_name=="Model_One":
train("Model_One", 128, 0.5, 30, 256, 0.0001)
elif model_name=="Model_Two":
train("Model_Two", 128, 0.5, 40, 64, 0.0001)
elif task=="test":
if model_name=="Model_One":
test_model(256, model_name)
elif model_name=="Model_Two":
test_model(64, model_name)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='CNN_Malware_Train_Test.py', description="Trains and Tests CNN classifiers")
parser.add_argument('--train', type=str)
parser.add_argument('--test', type=str)
args = parser.parse_args()
if args.train=="Model_One":
main("train", "Model_One")
elif args.train=="Model_Two":
main("train", "Model_Two")
if args.test=="Model_One":
main("test", "Model_One")
elif args.test=="Model_Two":
main("test", "Model_Two")