随机搜索CV不返回分数

2024-09-30 04:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个管道来运行预处理器和管理丢失的值等。但是当我尝试使用RandomizedSearchCV时,我被卡住了。 正常的GridsearchCV工作正常

它是一种监督学习方式和分类学习任务,预测/分类二元目标(1/0)

这是我的模型:

# Random Forest
RF = RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=None, 
                            min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0,
                            max_features='auto', max_leaf_nodes=None, random_state=1337)

这就是我建立管道并试图获得分数的地方,但是这可能不起作用

pipeline_RF = Pipeline(steps=[
        ('preprocessor', preprocessor),
        #('pca', pca),
        ('rf', RF)                          
])

print("\n------------ Randomized Search (Random Forest) ------------")

param_distributions = {
    'rf__n_estimators':  np.random.randint(1, 200, 10),
    'rf__max_depth': np.random.randint(1, 100, 10),
    'rf__min_samples_split': np.linspace(0.1, 1.0, 10, endpoint=True),      
    'rf__min_samples_leaf':  np.linspace(0.1, 0.5, 5, endpoint=True),
    'rf__criterion': ['entropy'],
    'rf__max_features': ['auto']
}

rscv = RandomizedSearchCV(pipeline_RF, param_distributions=param_distributions, cv = StratifiedKFold(n_splits=5), 
                          scoring="recall", n_iter=2, refit=True, n_jobs=-1, random_state=1337, return_train_score=True, verbose=10)

rscv.fit(X_train, y_train)
print("\nBest parameter (CV score=%0.3f):" % rscv.best_score_)
print("\Best Hyperparameters: ", rscv.best_params_)

y_pred = rscv.best_estimator_.predict(X_test)
print("\nPrecision, Recall, F1 and Support: ", precision_recall_fscore_support(y_test, y_pred, average='binary'))

错误消息如下,但对我帮助不大:

------------ Randomized Search (Random Forest) ------------
Fitting 5 folds for each of 2 candidates, totalling 10 fits

[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.
[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:    4.4s
[Parallel(n_jobs=-1)]: Done   4 tasks      | elapsed:    8.1s
[Parallel(n_jobs=-1)]: Done  10 out of  10 | elapsed:   18.4s finished


Best parameter (CV score=0.000):
\Best Hyperparameters:  {'rf__n_estimators': 135, 'rf__min_samples_split': 0.30000000000000004, 'rf__min_samples_leaf': 0.30000000000000004, 'rf__max_features': 'auto', 'rf__max_depth': 51, 'rf__criterion': 'entropy'}

Precision, Recall, F1 and Support:  (0.0, 0.0, 0.0, None)

/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py:1272: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))

它看起来像是设置了超参数(尽管每次运行时它们似乎都是相同的)

有人知道如何解决这个问题吗


Tags: andtrueparallelnpjobsrandomminmax
1条回答
网友
1楼 · 发布于 2024-09-30 04:35:47

正如desertnaut在评论中指出的那样,你的模型根本无法预测少数族裔。另一方面,您的代码是正确的。您可以通过以下方式对此进行验证:

根据您对BenReiniger的回复意见,我创建了一个虚拟数据集来再现您的情况:

from sklearn.datasets import make_classification

X, y = make_classification(n_samples=(32893+4176), n_classes=2, weights=[0.88, 0.12])
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.2, random_state=42)

此数据集与您的数据集具有相同的类和样本大小。当您在这个数据集上运行代码时,您将得到同样的警告。为什么呢?让我们将y_pred的结果作为pandas数据帧进行检查:

print(pd.DataFrame(y_pred).astype('category').describe())

# output
count   7414
unique     1
top        0
freq    7414

正如你所看到的,模型只预测了一个类。在这种情况下,定义为tp / (tp + fp)的正类的精度分数未定义,因为涉及到除零。这也是为什么您的警告告诉您:

Use `zero_division` parameter to control this behavior.

您应该能够在自己的数据集上验证这一点。此外,如果您使用另一个评分函数,如accuracy_score,您应该能够看到代码运行时没有警告或错误,并按预期返回评分。如果模型未预测任何正类,则某些指标只是未定义

这应该澄清一些事情。总之,您的代码是正确的。但是,您的模型对于预测任务的训练不够好,您需要正确处理类不平衡

相关问题 更多 >

    热门问题