svm 的机器学习网格搜索

Machine learning gridsearch for svm

我正在做一个项目,我需要计算 gridsearch 返回的最佳估计量。

parameters = {'gamma':[0.1, 0.5, 1, 10, 100], 'C':[1, 5, 10, 100, 1000]}

# TODO: Initialize the classifier
svr = svm.SVC()

# TODO: Make an f1 scoring function using 'make_scorer' 
f1_scorer = make_scorer(score_func)

# TODO: Perform grid search on the classifier using the f1_scorer as the scoring method
grid_obj = grid_search.GridSearchCV(svr, parameters, scoring=f1_scorer)

# TODO: Fit the grid search object to the training data and find the optimal parameters
grid_obj = grid_obj.fit(X_train, y_train)
pred = grid_obj.predict(X_test)
def score_func():
    f1_score(y_test, pred, pos_label='yes')

# Get the estimator
clf = grid_obj.best_estimator_

我不确定如何制作 f1_scorer 函数,因为我是在创建网格搜索对象后进行预测的。我无法在创建 obj 后声明 f1_scorer,因为 gridsearch 将其用作评分方法。请帮助我如何为 gridsearch 创建这个评分函数。

您传递给 make_scorer 的记分函数应该采用 y_truey_pred 作为参数。有了这些信息,您就拥有了计算分数所需的一切。然后 GridSearchCV 将适合并在内部为每组可能的参数调用评分函数,您不需要事先计算 y_pred。

它应该是这样的:

def score_func(y_true, y_pred):
    """Calculate f1 score given the predicted and expected labels"""
    return f1_score(y_true, y_pred, pos_label='yes')

f1_scorer = make_scorer(score_func)
GridSearchCV(svr, parameters, scoring=f1_scorer)
clf = svm.SVC()

# TODO: Make an f1 scoring function using 'make_scorer' 
f1_scorer = make_scorer(f1_score,pos_label='yes')

# TODO: Perform grid search on the classifier using the f1_scorer as the scoring method
grid_obj = GridSearchCV(clf,parameters,scoring=f1_scorer)

# TODO: Fit the grid search object to the training data and find the optimal parameters
grid_obj = grid_obj.fit(X_train, y_train)

# Get the estimator
clf = grid_obj.best_estimator_