This repository was archived by the owner on Apr 12, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 19
2nd phase Evaluations #19
Open
ashish493
wants to merge
10
commits into
OWASP:develop
Choose a base branch
from
ashish493:develop
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
78e6539
Merge pull request #7 from OWASP/develop
ashish493 70c42ff
added ml algos
ashish493 30e891a
added neural net classifiers
ashish493 9845211
Update nnclassifier.py
ashish493 a4bdbb5
update preprocessor
ashish493 f0ed85c
added neural_net functions
ashish493 9dcc992
changes in prediction app in view.py
ashish493 91da00e
added save model feature for pytorch
ashish493 b71be6e
Delete nnclassifier.py
ashish493 e3b20ef
Rename nnclassifier.py to nnclassifiers.py
ashish493 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,195 @@ | ||
#neural net classifier | ||
import torch | ||
import torch.nn as nn | ||
import torch.optim as optim | ||
from torch.autograd import Variable | ||
|
||
|
||
class CNN(nn.Module): | ||
def __init__(self, in_dim, n_class): | ||
super(CNN, self).__init__() | ||
|
||
self.conv = nn.Sequential( | ||
nn.Conv2d(in_dim, 6, 3, stride=1, padding=1), | ||
nn.BatchNorm2d(6), | ||
nn.ReLU(True), | ||
nn.Conv2d(6, 16, 3, stride=1, padding=0), | ||
nn.BatchNorm2d(16), | ||
nn.ReLU(True), | ||
nn.MaxPool2d(2, 2) | ||
) | ||
|
||
self.fc = nn.Sequential( | ||
nn.Linear(144, 512), | ||
nn.Linear(512, 256), | ||
nn.Linear(256, n_class) | ||
) | ||
|
||
def forward(self, x): | ||
out = self.conv(x) | ||
out = out.view(out.size(0), -1) | ||
out = self.fc(out) | ||
return out | ||
|
||
|
||
class RNNModel(nn.Module): | ||
|
||
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): | ||
super(RNNModel, self).__init__() | ||
self.hidden_dim = hidden_dim | ||
self.layer_dim = layer_dim | ||
self.rnn = nn.RNN(input_dim, hidden_dim, layer_dim, batch_first=True, nonlinearity='relu') | ||
|
||
self.fc = nn.Linear(hidden_dim, output_dim) | ||
|
||
def forward(self, x): | ||
|
||
h0 = Variable(torch.zeros(self.layer_dim, x.size(0), self.hidden_dim)) | ||
|
||
|
||
out, hn = self.rnn(x, h0) | ||
out = self.fc(out[:, -1, :]) | ||
return out | ||
|
||
|
||
|
||
|
||
class Autoencoder(nn.Module): | ||
def __init__(self): | ||
super(Autoencoder,self).__init__() | ||
|
||
self.encoder = nn.Sequential( | ||
nn.Conv2d(3, 6, kernel_size=5), | ||
nn.ReLU(True), | ||
nn.Conv2d(6,16,kernel_size=5), | ||
nn.ReLU(True)) | ||
self.decoder = nn.Sequential( | ||
nn.ConvTranspose2d(16,6,kernel_size=5), | ||
nn.ReLU(True), | ||
nn.ConvTranspose2d(6,3,kernel_size=5), | ||
nn.ReLU(True)) | ||
|
||
def forward(self,x): | ||
x = self.encoder(x) | ||
x = self.decoder(x) | ||
return x | ||
|
||
|
||
class SOM(nn.Module): | ||
|
||
def __init__(self, m, n, dim, niter, alpha=None, sigma=None): | ||
super(SOM, self).__init__() | ||
self.m = m | ||
self.n = n | ||
self.dim = dim | ||
self.niter = niter | ||
if alpha is None: | ||
self.alpha = 0.3 | ||
else: | ||
self.alpha = float(alpha) | ||
if sigma is None: | ||
self.sigma = max(m, n) / 2.0 | ||
else: | ||
self.sigma = float(sigma) | ||
|
||
self.weights = torch.randn(m*n, dim) | ||
self.locations = torch.LongTensor(np.array(list(self.neuron_locations()))) | ||
self.pdist = nn.PairwiseDistance(p=2) | ||
|
||
def get_weights(self): | ||
return self.weights | ||
|
||
def get_locations(self): | ||
return self.locations | ||
|
||
def neuron_locations(self): | ||
for i in range(self.m): | ||
for j in range(self.n): | ||
yield np.array([i, j]) | ||
|
||
def map_vects(self, input_vects): | ||
to_return = [] | ||
for vect in input_vects: | ||
min_index = min([i for i in range(len(self.weights))], | ||
key=lambda x: np.linalg.norm(vect-self.weights[x])) | ||
to_return.append(self.locations[min_index]) | ||
|
||
return to_return | ||
|
||
def forward(self, x, it): | ||
dists = self.pdist(torch.stack([x for i in range(self.m*self.n)]), self.weights) | ||
_, bmu_index = torch.min(dists, 0) | ||
bmu_loc = self.locations[bmu_index,:] | ||
bmu_loc = bmu_loc.squeeze() | ||
|
||
|
||
# Neural network parameters " would be collected from JSON Config" | ||
batch_size = 128 | ||
learning_rate = 1e-2 | ||
num_epoches = 5 | ||
USE_GPU = torch.cuda.is_available() | ||
|
||
model = CNN(1, 23) #would be set in config | ||
#model = SOM(1, 23) | ||
#model = RNN(1, 23) | ||
#model = AE(1, 23) | ||
|
||
def neural_train(): | ||
|
||
global model | ||
|
||
if USE_GPU: | ||
model = model.cuda() | ||
|
||
criterion = nn.CrossEntropyLoss() | ||
optimizer = optim.SGD(model.parameters(), lr=learning_rate) | ||
|
||
for epoch in range(num_epoches): | ||
print('epoch {}'.format(epoch + 1)) | ||
print('*' * 10) | ||
running_loss = 0.0 | ||
running_acc = 0.0 | ||
for i, data in enumerate(dataset.train_dataloader, 1): | ||
img, label = data | ||
if USE_GPU: | ||
img = img.cuda() | ||
label = label.cuda() | ||
img = Variable(img) | ||
label = Variable(label) | ||
# Spread forward | ||
out = model(img) | ||
loss = criterion(out, label) | ||
running_loss += loss.item() * label.size(0) | ||
_, pred = torch.max(out, 1) | ||
num_correct = (pred == label).sum() | ||
accuracy = (pred == label).float().mean() | ||
running_acc += num_correct.item() | ||
# Spread backward | ||
optimizer.zero_grad() | ||
loss.backward() | ||
optimizer.step() | ||
|
||
print('Finish {} epoch, Loss: {:.6f}, Acc: {:.6f}'.format( | ||
epoch + 1, running_loss / (len(dataset.train_dataset)), running_acc / (len( | ||
dataset.train_dataset)))) | ||
model.eval() | ||
eval_loss = 0 | ||
eval_acc = 0 | ||
for data in dataset.test_dataloader: | ||
img, label = data | ||
if USE_GPU: | ||
img = Variable(img, volatile=True).cuda() | ||
label = Variable(label, volatile=True).cuda() | ||
else: | ||
img = Variable(img, volatile=True) | ||
label = Variable(label, volatile=True) | ||
out = model(img) | ||
loss = criterion(out, label) | ||
eval_loss += loss.item() * label.size(0) | ||
_, pred = torch.max(out, 1) | ||
num_correct = (pred == label).sum() | ||
eval_acc += num_correct.item() | ||
print('Test Loss: {:.6f}, Acc: {:.6f}'.format(eval_loss / (len( | ||
dataset.test_dataset)), eval_acc / (len(dataset.test_dataset)))) | ||
torch.save(model, filepath) | ||
print() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one is for saving the models