Calculate accuracy of autoencoder

First I train the autoencoder for number of epochs for normal images and save the model. Then I load it and evaluate it for validation dataset consist of normal and abnormal images and calculate the reconstruction loss for each image in validation set. Then I add the each reconstruction loss and the label of that image (normal or abnormal) to two arrays. Then I use sklearn, svm to to fit the validation set. Then I predict the test images using svm and calculate the accuracy.

for data in dataloader:
images, label, paths = data
x = images.to(device)
with torch.set_grad_enabled(False):
x_reconstructed = model(x)
for i in range(len(x)):
reconstructed_loss = reconstruct_loss_fn(x_reconstructed[i], x[i])
if test == “abnormal”:
label = 0
if test == “normal”:
label = 1
trainDdata.append(reconstructed_loss)
targets.append(label)

model1 = svm.SVC()
trainDdata= (np.array(trainDdata)).reshape(-1, 1)
targets= (np.array(targets)).reshape(-1, 1)
model1.fit(trainDdata, targets.ravel())

testDdata= (np.array(testDdata)).reshape(-1, 1)
testTargets= (np.array(testTargets)).reshape(-1, 1)
targets2 = model1.predict(testDdata)
targets2= (np.array(targets2)).reshape(-1, 1)
equals = targets2 == testTargets.reshape(*targets2.shape)
print(f"Accuracy = {np.mean(equals.astype(int))*100:.3f}%")
I’m new to pytorch and I have a doubt whether this is correct?

1 Like