1

我正在创建一个 GRU 来预测来自设备的流量数据包的数据是否被认为是安全的或异常的。我计划通过仅在安全/正常操作数据上训练模型然后让它检查它认为新的看不见的流量是什么来做到这一点(测试)。我希望只在安全数据(一类)上进行训练,因为攻击可以采取多种形式,我不想在标记的攻击数据上训练模型,然后让它错过我没有训练过的攻击类型(基本上我想过度拟合正常的操作数据)。因此,我需要它能够检查传入的未标记数据是否与它已经训练过的一类匹配(即传入的数据是否与设备的正常操作匹配)或者它是否异常。

我遇到的问题是,由于该模型仅在一个类上进行训练,因此很难将异常的看不见的数据与正常数据区分开来,并且几乎将所有它认为正常的数据都视为正常(与它所训练的类相同)。

因此,如果有人有任何想法或可以指出我通过模型实现的方式中的缺陷,我将不胜感激。

# Imports
import pandas as pd
import numpy as np
import torch
import torchvision  # torch package for vision related things
import torch.nn.functional as F  # Parameterless functions, like (some) activation functions
import torchvision.datasets as datasets  # Standard datasets
import torchvision.transforms as transforms  # Transformations we can perform on our dataset for augmentation
from torch import optim  # For optimizers like SGD, Adam, etc.
from torch import nn  # All neural network modules
from torch.utils.data import Dataset, DataLoader  # Gives easier dataset managment by creating mini batches etc.
from tqdm import tqdm  # For a nice progress bar
from sklearn.preprocessing import StandardScaler

# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Hyperparameters
input_size = 24
hidden_size = 128
num_layers = 1
num_classes = 2
sequence_length = 1
learning_rate = 0.005
batch_size = 8
num_epochs = 5

# Recurrent neural network with GRU (many-to-one)
class RNN_GRU(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(RNN_GRU, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size * sequence_length, num_classes)

    def forward(self, x):
        # Set initial hidden and cell states
        x = x.unsqueeze(1)
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
        # Forward propagate GRU
        out, _ = self.gru(x, h0)
        out = out[:, -1, :]

        # Decode the hidden state of the last time step
        out = self.fc(out)
        return out

class MyDataset(Dataset):
 
  def __init__(self,file_name):
    stats_df=pd.read_csv(file_name)
 
    x=stats_df.iloc[:,0:24].values
    y=stats_df.iloc[:,24].values
 
    self.x_train=torch.tensor(x,dtype=torch.float32)
    self.y_train=torch.tensor(y,dtype=torch.float32)
 
  def __len__(self):
    return len(self.y_train)
   
  def __getitem__(self,idx):
    return self.x_train[idx],self.y_train[idx]

nomDs=MyDataset("nomStats.csv")
atkDs=MyDataset("atkStats.csv")
train_loader=DataLoader(dataset=nomDs,batch_size=batch_size)
test_loader=DataLoader(dataset=atkDs,batch_size=batch_size)

# Initialize network 
model = RNN_GRU(input_size, hidden_size, num_layers, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Train Network
for epoch in range(num_epochs):
    for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
        # Get data to cuda if possible
        data = data.to(device=device).squeeze(1)
        targets = targets.to(device=device)
        targets = targets.to(dtype=torch.long)

        # forward
        scores = model(data)
        loss = criterion(scores, targets)

        # backward
        optimizer.zero_grad()
        loss.backward()

        # gradient descent update step/adam step
        optimizer.step()

# Check accuracy on training & test to see how good our model
def check_accuracy(loader, model):
    num_correct = 0
    num_samples = 0

    # Set model to eval
    model.eval()

    with torch.no_grad():
        for x, y in loader:
            x = x.to(device=device).squeeze(1)
            y = y.to(device=device)

            scores = model(x)
            _, predictions = scores.max(1)
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0)

    # Toggle model back to train
    model.train()
    return num_correct / num_samples

print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}%")
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}%")
4

0 回答 0