我遇到了一个问题,使用GridSearchCV微调超参数并没有明显提高我的分类器性能。我认为提升幅度应该会更大。我当前代码所能获得的最大分类器提升大约是±0.03。我的数据集有八列,且结果是非平衡的二元结果。我使用f1作为评分标准,并使用10折的KFold。如果有人能指出哪里有问题,我应该检查哪些方面,我将不胜感激!谢谢!
我使用以下代码:
model_parameters = { "GaussianNB": { }, "DecisionTreeClassifier": { 'min_samples_leaf': range(5, 9), 'max_depth': [None, 0, 1, 2, 3, 4] }, "KNeighborsClassifier": { 'n_neighbors': range(1, 10), 'weights': ["distance", "uniform"] }, "SVM": { 'kernel': ["poly"], 'C': np.linspace(0, 15, 30) }, "LogisticRegression": { 'C': np.linspace(0, 15, 30), 'penalty': ["l1", "l2", "elasticnet", "none"] }}X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)n_splits = 10scoring_method = make_scorer(lambda true_target, prediction: f1_score(true_target, prediction, average="micro"))cv = KFold(n_splits=n_splits, random_state=random_state, shuffle=True)for model_name, parameters in model_parameters.items(): # Models is a dict with 5 classifiers model = models[model_name] grid_search = GridSearchCV(model, parameters, cv=cv, n_jobs=-1, scoring=scoring_method, verbose=False).fit(X_train, y_train) cvScore = cross_val_score(grid_search.best_estimator_, X_test, y_test, cv=cv, scoring='f1').mean() classDict[model_name] = cvScore
回答:
如果你的类别不平衡,当你进行KFold时,你应该保持两个目标之间的比例。
折叠不平衡可能会导致非常差的结果
请查看分层K折交叉验证器
提供训练/测试索引以将数据拆分为训练/测试集。
这种交叉验证对象是KFold的一种变体,它返回分层的折叠。通过保留每个类别的样本百分比来制作折叠。
还有很多处理不平衡数据集的技术。根据上下文:
- 上采样少数类(例如使用sklearn的resample)
- 下采样多数类(这个库也有一些有用的工具来进行上下采样)
- 用你特定的机器学习模型处理不平衡
例如,在SVC中,创建模型时有一个参数,class_weight='balanced'
clf_3 = SVC(kernel='linear', class_weight='balanced', # 惩罚 probability=True)
这将对少数类的错误进行更多的惩罚。
你可以这样更改你的配置:
"SVM": { 'kernel': ["poly"], 'C': np.linspace(0, 15, 30), 'class_weight': 'balanced' }
对于LogisticRegression,你可以设置权重,反映你类别的比例
LogisticRegression(class_weight={0:1, 1:10}) # 如果问题是二元的
以这种方式更改网格搜索字典:
"LogisticRegression": { 'C': np.linspace(0, 15, 30), 'penalty': ["l1", "l2", "elasticnet", "none"], 'class_weight':{0:1, 1:10} }
无论如何,方法取决于所使用的模型。例如,对于神经网络,你可以更改损失函数,以加权计算的方式惩罚少数类(与逻辑回归相同)