我想通过对不平衡数据集使用网格搜索来优化 SVC 的超参数 C 和 Gamma。到目前为止,我已经使用了 class_weights='balanced' 并根据 f1 分数的平均值选择了最佳超参数。然而,数据集非常不平衡,即如果我选择 cv=10 的 GridSearchCV,那么一些少数类不会在验证数据中表示。我正在考虑使用 SMOTE,但我发现这里的问题是我必须设置 k_neighbors=1,因为在某些少数类中通常只有 1-2 个样本。有谁知道如何在这种情况下优化超参数?还有其他选择吗?
非常感谢您的每一个提示
最佳答案
I would like to optimize the hyperparameters C and Gamma of an SVC by using grid search for an unbalanced data set. Does anyone have a tip how to optimized the hyperparameters in this case?
您可以使用 GridSearchCV() 函数执行以下操作:
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.1, 5, 50, 100],
'gamma': [1, 0.5, 0.1, 0.01]}
model = GridSearchCV(SVC(), param_grid, refit = True)
model.fit(X_train, y_train)
您可以使用RandomizedSearchCV以便探索更多选择。
I'm thinking of using SMOTE, but I see the problem here that I would have to set k_neighbors=1
你试过吗ADASYN ?
Are there any alternatives?
当我真的迷失时,我会尝试“最后的资源”。这是一个名为tpot的工具。
只是做一个这样的例子:
tpot = TPOTClassifier(generations=5, population_size=50, scoring='roc_auc', verbosity=2, random_state=42)
tpot.fit(X_train, y_train)
print(tpot.score(X_test, y_test))
tpot.export('tpot_results.py')
它将输出一个 sklearn 代码,带有算法和管道,在本例中 tpot_results.py 将是:
tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)
features = tpot_data.drop('target', axis=1)
training_features, testing_features, training_target, testing_target = \
train_test_split(features, tpot_data['target'], random_state=42)
# Average CV score on the training set was: 0.9826086956521738
exported_pipeline = make_pipeline(
Normalizer(norm="l2"),
KNeighborsClassifier(n_neighbors=5, p=2, weights="distance")
)
# Fix random state for all the steps in exported pipeline
set_param_recursive(exported_pipeline.steps, 'random_state', 42)
exported_pipeline.fit(training_features, training_target)
results = exported_pipeline.predict(testing_features)
使用此工具时要小心过度拟合问题,但这是我可以推荐您的一种替代方案。
关于scikit-learn - 不平衡的数据集 - 如何通过网格搜索优化超参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59953040/