def anomaly_detection(test_img, g=None, d=None): model = anogan.anomaly_detector(g=g, d=d) ano_score, similar_img = anogan.compute_anomaly_score(model, test_img.reshape(1, 28, 28, 1), iterations=500, d=d) # anomaly area, 255 normalization np_residual = test_img.reshape(28,28,1) - similar_img.reshape(28,28,1) np_residual = (np_residual + 2)/4 np_residual = (255*np_residual).astype(np.uint8) original_x = (test_img.reshape(28,28,1)*127.5+127.5).astype(np.uint8) similar_x = (similar_img.reshape(28,28,1)*127.5+127.5).astype(np.uint8) original_x_color = cv2.cvtColor(original_x, cv2.COLOR_GRAY2BGR) residual_color = cv2.applyColorMap(np_residual, cv2.COLORMAP_JET) show = cv2.addWeighted(original_x_color, 0.3, residual_color, 0.7, 0.) return ano_score, original_x, similar_x, show
X_train = (X_train.astype(np.float32) - 127.5) / 127.5 X_test = (X_test.astype(np.float32) - 127.5) / 127.5 y_train = y_train[:, 0] y_test = y_test[:, 0] idx_normal = np.any(y_train[..., None] == np.array([0])[None, ...], axis=1) X_train = X_train[idx_normal] perm_test = np.random.permutation(len(X_train)) X_train = X_train[perm_test] ## 3. other class anomaly detection test_imgs = X_train[0:500] score_for_2 = [] # test_img = np.random.uniform(-1,1, (28,28,1)) model = anogan.anomaly_detector(g=None, d=None) for i in range(np.shape(test_imgs)[0]): # start = cv2.getTickCount() score = anogan.compute_anomaly_score(model, test_imgs[i].reshape(1, 32, 32, 3), iterations=500, d=None) # time = (cv2.getTickCount() - start) / cv2.getTickFrequency() * 1000 print('%d label, %d : done' % (1, i), '%.2f' % score) score_for_2.append(score) score_for_2 = np.sort(score_for_2)[::-1] print(score_for_2) import pickle pickle.dump(score_for_2, open("cifar10_score.pickle", "wb"))