Nic*_*Gao 2 python grid-search
我正在研究GridSearch方法来调整Desicion树模型或随机森林模型的参数.在阅读了波士顿住房价格的例子后,我发现我无法运行该示例的代码.以下代码是示例的GridSearch代码.问题是ValueError: Parameter values for parameter (max_depth) need to be a sequence.我搜索了某些示例,但是,params这些示例中的变量几乎以相同的格式定义,这可能导致此错误.我认为作者想要创建一个带键的字典总是"max_depth",但值会从1到10不等.我无法解决这个问题.有人可以帮助我吗?
def fit_model(X, y):
""" Performs grid search over the 'max_depth' parameter for a
decision tree regressor trained on the input data [X, y]. """
# Create cross-validation sets from the training data
cv_sets = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.20, random_state = 0)
print (cv_sets)
# Create a decision tree regressor object
regressor = DecisionTreeRegressor()
# Create a dictionary for the parameter 'max_depth' with a range from 1 to 10
params = {'max_depth': range(1,11)}
# Transform 'performance_metric' into a scoring function using 'make_scorer'
scoring_fnc = make_scorer(performance_metric)
# Create the grid search object
grid = GridSearchCV(estimator=regressor, param_grid=params, scoring=scoring_fnc, cv=cv_sets)
# Fit the grid search object to the data to compute the optimal model
grid = grid.fit(X, y)
# Return the optimal model after fitting the data
return grid.best_estimator_
Run Code Online (Sandbox Code Playgroud)
我的理论是:该grid-search模块是为python 2设计的,其中:
range 生成一个 listrange可以检查的类型所以range从Python 3 传递一个不起作用的角落,带有令人困惑的消息.
我想我通过查看第348行的源代码找到了原因(和修复):
check = [isinstance(v, k) for k in (list, tuple, np.ndarray)]
if True not in check:
raise ValueError("Parameter values for parameter ({0}) need "
"to be a sequence.".format(name))
Run Code Online (Sandbox Code Playgroud)
在python 3中,range 是一个序列,但由于它不再生成list,它不被接受,grid-search因为代码测试对象类型明显(所以如果你问我:)错误消息稍微关闭).此外,我很确定如果代码也包含range在类型测试中,其余的代码将非常有效,因为range非常接近模拟list,而不生成任何代码.
修复就是强制迭代,例如:
params = {'max_depth': list(range(1,11))}
Run Code Online (Sandbox Code Playgroud)
(tuple或numpy数组也可以)
要修复grid-search,可以这样做:( for k in (list, tuple, np.ndarray, range)但是在python 2中可能会中断,并且这里可能存在一些python 2/3兼容性要求)
其他修复方法是:
if isinstance(k,(list, tuple, np.ndarray, range)):作为isinstance已经接受tuple,没有必要与列表理解产生布尔值的复杂结构.| 归档时间: |
|
| 查看次数: |
936 次 |
| 最近记录: |