talreiss / Mean-Shifted-Anomaly-Detection

Mean-Shifted Contrastive Loss for Anomaly Detection (AAAI 2023)
https://arxiv.org/pdf/2106.03844.pdf
Other
117 stars 23 forks source link

Steps for inference #11

Closed venki-lfc closed 1 year ago

venki-lfc commented 1 year ago

Hi, First of all, thanks for a great paper. It is very well written. I have a doubt regarding the inferencing after the ResNet model has been trained. I have trained the model for 20 epochs on Cifar-10 dataset with ResNet-152. And now I am trying to classify examples as anomalous or not. Could you please tell me if I'm doing the inference steps correctly?

# Set the device and load the model

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = utils.Model(152)
model.load_state_dict(torch.load(r"./Resnet152_Epochs20.pt", map_location=torch.device('cpu')))
model = model.to(device)

#Load the ddataset train_loader, test_loader, train_loader_1 = utils.get_loaders(dataset='cifar10', label_class=0, batch_size=32, backbone=152)

#Get the train and test feature space

train_feature_space = []
with torch.no_grad():
    for (imgs, _) in tqdm(train_loader, desc='Train set feature extracting'):
        imgs = imgs.to(device)
        features = model(imgs)
        train_feature_space.append(features)
    train_feature_space = torch.cat(train_feature_space, dim=0).contiguous().cpu().numpy()
test_feature_space = []
test_labels = []
with torch.no_grad():
    for (imgs, labels) in tqdm(test_loader, desc='Test set feature extracting'):
        imgs = imgs.to(device)
        features = model(imgs)
        test_feature_space.append(features)
        test_labels.append(labels)
    test_feature_space = torch.cat(test_feature_space, dim=0).contiguous().cpu().numpy()
    test_labels = torch.cat(test_labels, dim=0).cpu().numpy()

#Calculate the distances of each test sample to the train data distances = utils.knn_score(train_feature_space, test_feature_space)

Now do I have to set a threshold for the distances and then classify images as anomalous or not?

talreiss commented 1 year ago

That's exactly right.