Scikit learn scikit learn(sklearn)中的GridSearchCV:TypeError:';KFold';对象是不可编辑的

Scikit learn scikit learn(sklearn)中的GridSearchCV:TypeError:';KFold';对象是不可编辑的,scikit-learn,svm,cross-validation,grid-search,Scikit Learn,Svm,Cross Validation,Grid Search,我试图使用GridSearchCV()为SVR()估计器找到C&gamma的最佳值,但我得到了这个错误 TypeError:“KFold”对象不可编辑 这就是代码 from sklearn.grid_search import GridSearchCV from sklearn.model_selection import KFold C_range = np.logspace(-2, 10, 13) gamma_range = np.logspace(-9, 3, 13) param_grid

我试图使用GridSearchCV()为SVR()估计器找到C&gamma的最佳值,但我得到了这个错误

TypeError:“KFold”对象不可编辑

这就是代码

from sklearn.grid_search import GridSearchCV
from sklearn.model_selection import KFold
C_range = np.logspace(-2, 10, 13)
gamma_range = np.logspace(-9, 3, 13)
param_grid = dict(gamma=gamma_range, C=C_range)
cv = KFold(n_splits=5, shuffle=False, random_state=None)
grid = GridSearchCV(SVR(kernel='rbf'), param_grid=param_grid, cv=cv)
grid.fit(X, y)

print("The best parameters are %s with a score of %0.2f"
  % (grid.best_params_, grid.best_score_))

cv
是您案例中的一个对象。 您应该使用
KFold
来创建数据批,并将这些批传递给
cv
参数中的
GridSearchCV

下面是一个关于如何使用
KFold
创建拆分的示例:

>>> from sklearn.model_selection import KFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = KFold(n_splits=2)
>>> kf.get_n_splits(X)
2
>>> print(kf)  
KFold(n_splits=2, random_state=None, shuffle=False)
>>> for train_index, test_index in kf.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]

类似问题由以下人员解决:

from sklearn.grid_search import GridSearchCV
更换:

from sklearn.grid_search import GridSearchCV

from sklearn.model_selection import GridSearchCV