AttributeError: 'numpy.ndarray' object has no attribute '_iter_test_masks'

AttributeError: 'numpy.ndarray' object has no attribute '_iter_test_masks'

我正在尝试使用 sklearn GridSearchCV 执行 K 折交叉验证 select KernelDensity 估计的带宽。

当我执行 grid.fit(data) 时,我收到错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\utils\validation.py", line 73, in inner_f
    return f(**kwargs)
  File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 736, in fit
    self._run_search(evaluate_candidates)
  File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 1188, in _run_search
    evaluate_candidates(ParameterGrid(self.param_grid))
  File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 714, in evaluate_candidates
    in product(candidate_params,
  File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_split.py", line 80, in split
    for test_index in self._iter_test_masks(X, y, groups):
AttributeError: 'numpy.ndarray' object has no attribute '_iter_test_masks'

这是我的代码:

import numpy as np
from sklearn.model_selection import GridSearchCV, LeaveOneOut

train = np.random.rand(12,2)
target = np.array([0,0,1,2,3,3,3,4,5,5,6,6])

bw = np.linspace(0.01,0.1,10)
grid = GridSearchCV(KernelDensity(kernel='gaussian'),
                    {'bandwidth': bw},
                    cv=LeaveOneOut)
grid.fit(train,target[:,None])

您只是忘记在 GridSearchCV 定义中实例化 LeaveOneOut 交叉验证器。

train = np.random.rand(12,2)
target = np.array([0,0,1,2,3,3,3,4,5,5,6,6])

bw = np.linspace(0.01,0.1,10)
grid = GridSearchCV(KernelDensity(kernel='gaussian'),
                    {'bandwidth': bw},
                    cv=LeaveOneOut() # <-- typo was here
)

grid.fit(train,target[:,None])

这将解决问题。