2016-12-31 70 views
2

我试图找到最佳值的C &伽马SVR()估计使用GridSearchCV(),但我得到这个错误RBF SVM参数在scikit中使用GridSearchCV()学习.... TypeError:'KFold'对象不可迭代

类型错误: '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_)) 

回答

1

cv是你的情况的对象。 您应该使用KFold来创建批次数据,并将这些批次传递给GridSearchCVcv参数。

这里就如何创建一个分裂例如,使用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] 
5

要解决类似的问题:

更换:

from sklearn.grid_search import GridSearchCV 

from sklearn.model_selection import GridSearchCV