# Cross-Validation for Unsupervised Anomaly Detection with Isolation Forest

I am wondering whether I can perform any kind of Cross-Validation or GridSearchCV for unsupervised learning. The thing is that I have the ground truth labels (but since it is unsupervised I just drop them for training and then reuse them for measuring accuracy, auc, aucpr, f1-score over the test set).

Is there any way to do this?

• What do you mean by "way"? A specific method or a concept/pseudo-code?
– WBM
Mar 8, 2021 at 13:50
• I don't need neither a specific method nor pseudo-code, I was just wondering if this is possible and if so, how would it work; maybe some reference about it, etc. Mar 9, 2021 at 9:01

Yes - you can use scikit-learn's GridSearchCV with an unsupervised algorithm. Since scikit-learn's Isolation Forest does not have a score function, a custom scoring function has to be implemented. It would something like this:

import numpy as np
from sklearn.ensemble        import IsolationForest
from sklearn.model_selection import GridSearchCV

def scorer(estimator, X):
"Custom scoring function"
return np.mean(estimator.score_samples(X))

isolation_forest = GridSearchCV(IsolationForest(), scoring=scorer)
isolation_forest.fit(X)