GridSearchCV可以用于无监督学习吗



我正在尝试构建一个异常值检测器来查找测试数据中的异常值。这些数据会有所不同(测试通道越多,测试时间越长(。

首先,我应用了列车测试分割,因为我想对列车数据使用网格搜索来获得最佳结果。这是来自多个传感器的时间序列数据,我事先删除了时间列。

X shape : (25433, 17)
y shape : (25433, 1)
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.33,
random_state=(0))

之后进行标准化,然后我将它们改为int数组,因为GridSearch似乎不喜欢连续数据。这当然可以做得更好,但我希望在优化编码之前先这样做。

'X'
mean = StandardScaler().fit(X_train)
X_train = mean.transform(X_train)
X_test = mean.transform(X_test)
X_train = np.round(X_train,2)*100
X_train = X_train.astype(int)
X_test = np.round(X_test,2)*100
X_test = X_test.astype(int)
'y'
yeah = StandardScaler().fit(y_train)
y_train = yeah.transform(y_train)
y_test = yeah.transform(y_test)
y_train = np.round(y_train,2)*100
y_train = y_train.astype(int)
y_test = np.round(y_test,2)*100
y_test = y_test.astype(int)

我选择IsoForrest是因为它速度快,结果很好,可以处理巨大的数据集(我目前只使用一大块数据进行测试(。SVM也可能是我想要检查的一个选项。然后我设置了GridSearchCV

clf = IForest(random_state=47, behaviour='new',
n_jobs=-1)
param_grid = {'n_estimators': [20,40,70,100], 
'max_samples': [10,20,40,60], 
'contamination': [0.1, 0.01, 0.001], 
'max_features': [5,15,30], 
'bootstrap': [True, False]}
fbeta = make_scorer(fbeta_score,
average = 'micro',
needs_proba=True,
beta=1)
grid_estimator = model_selection.GridSearchCV(clf, 
param_grid,
scoring=fbeta,
cv=5,
n_jobs=-1,
return_train_score=True,
error_score='raise',
verbose=3)
grid_estimator.fit(X_train, y_train)

问题:

GridSearchCV需要一个y论点,所以我认为这只适用于监督学习?如果我运行这个,我会得到以下错误,我不理解:

ValueError: Classification metrics can't handle a mix of multiclass and continuous-multioutput targets

您可以使用GridSearchCV进行无监督学习,但定义一个对问题有意义的评分指标通常很难。

下面是文档中的一个例子,它使用网格搜索KernelDensity,这是一个无监督的估计器。它工作起来没有问题,因为这个估计器有一个score方法(docs(。

在您的情况下,由于IsolationForest没有score方法,您需要定义一个自定义得分手作为搜索的scoring方法。这个问题和这个问题都有答案,但我认为给出的指标不一定有意义。不幸的是,我没有一个有用的异常值检测指标;这是一个更适合数据科学或统计stackexchange网站的问题。

同意@Ben Reiniger的回答,它与其他SO关于这个主题的帖子有很好的链接
您可以尝试创建一个自定义得分手,假设您可以使用y_train。这并不是严格意义上的unsupervised

这里是一个例子,其中R2得分被用作得分度量。

from sklearn.metrics import r2_score
def scorer_f(estimator, X_train,Y_train):
y_pred=estimator.predict(Xtrain)
return r2_score(Y_train, y_pred)

然后你就可以正常使用了。

clf = IForest(random_state=47, behaviour='new',
n_jobs=-1)
param_grid = {'n_estimators': [20,40,70,100], 
'max_samples': [10,20,40,60], 
'contamination': [0.1, 0.01, 0.001], 
'max_features': [5,15,30], 
'bootstrap': [True, False]}
grid_estimator = model_selection.GridSearchCV(clf, 
param_grid,
scoring=scorer_f,
cv=5,
n_jobs=-1,
return_train_score=True,
error_score='raise',
verbose=3)
grid_estimator.fit(X_train, y_train)

最新更新