1

グリッド検索の実行中にエラーが発生しました。グリッド検索が実際にどのように機能するかについての誤解が原因である可能性があると思います。

現在、別のスコアリング関数を使用して最適なパラメーターを評価するためにグリッド検索が必要なアプリケーションを実行しています。RandomForestClassifier を使用して、大きな X データセットを 0 と 1 のリストである特性ベクトル Y に適合させています。(完全にバイナリ)。私のスコアリング関数 (MCC) では、予測入力と実際の入力が完全にバイナリである必要があります。ただし、何らかの理由で ValueError: multiclass is not supported が発生し続けます。

私の理解では、グリッド検索はデータセットに対して交差検証を行い、交差検証に基づく予測入力を考え出し、特性化ベクトルと予測を関数に挿入します。私の特性ベクトルは完全にバイナリであるため、予測ベクトルもバイナリである必要があり、スコアを評価する際に問題は発生しません。(グリッド検索を使用せずに) 単一の定義済みパラメーターを使用してランダム フォレストを実行すると、予測データと特性ベクトルを MCC スコアリング関数に挿入すると、問題なく実行されます。そのため、グリッド検索を実行するとエラーが発生する方法について少し迷っています。

データのスナップショット:

        print len(X)
        print X[0]
        print len(Y)
        print Y[2990:3000]
17463699
[38.110903683955435, 38.110903683955435, 38.110903683955435, 9.899495124816895, 294.7808837890625, 292.3835754394531, 293.81494140625, 291.11065673828125, 293.51739501953125, 283.6424865722656, 13.580912590026855, 4.976086616516113, 1.1271398067474365, 0.9465181231498718, 0.5066819190979004, 0.1808401197195053, 0.0]
17463699
[0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]

コード:

def overall_average_score(actual,prediction):
    precision = precision_recall_fscore_support(actual, prediction, average = 'binary')[0]
    recall = precision_recall_fscore_support(actual, prediction, average = 'binary')[1]
    f1_score = precision_recall_fscore_support(actual, prediction, average = 'binary')[2]
    total_score = matthews_corrcoef(actual, prediction)+accuracy_score(actual, prediction)+precision+recall+f1_score
    return total_score/5

grid_scorer = make_scorer(overall_average_score, greater_is_better=True)
parameters = {'n_estimators': [10,20,30], 'max_features': ['auto','sqrt','log2',0.5,0.3], }
random  = RandomForestClassifier()
clf = grid_search.GridSearchCV(random, parameters, cv = 5, scoring = grid_scorer)
clf.fit(X,Y)

エラー:

ValueError                                Traceback (most recent call last)
<ipython-input-39-a8686eb798b2> in <module>()
     18 random  = RandomForestClassifier()
     19 clf = grid_search.GridSearchCV(random, parameters, cv = 5, scoring = grid_scorer)
---> 20 clf.fit(X,Y)
     21 
     22 

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/grid_search.pyc in fit(self, X, y)
    730 
    731         """
--> 732         return self._fit(X, y, ParameterGrid(self.param_grid))
    733 
    734 

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/grid_search.pyc in _fit(self, X, y, parameter_iterable)
    503                                     self.fit_params, return_parameters=True,
    504                                     error_score=self.error_score)
--> 505                 for parameters in parameter_iterable
    506                 for train, test in cv)
    507 

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    657             self._iterating = True
    658             for function, args, kwargs in iterable:
--> 659                 self.dispatch(function, args, kwargs)
    660 
    661             if pre_dispatch == "all" or n_jobs == 1:

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in dispatch(self, func, args, kwargs)
    404         """
    405         if self._pool is None:
--> 406             job = ImmediateApply(func, args, kwargs)
    407             index = len(self._jobs)
    408             if not _verbosity_filter(index, self.verbose):

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __init__(self, func, args, kwargs)
    138         # Don't delay the application, to avoid keeping the input
    139         # arguments in memory
--> 140         self.results = func(*args, **kwargs)
    141 
    142     def get(self):

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/cross_validation.pyc in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, error_score)
   1476 
   1477     else:
-> 1478         test_score = _score(estimator, X_test, y_test, scorer)
   1479         if return_train_score:
   1480             train_score = _score(estimator, X_train, y_train, scorer)

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/cross_validation.pyc in _score(estimator, X_test, y_test, scorer)
   1532         score = scorer(estimator, X_test)
   1533     else:
-> 1534         score = scorer(estimator, X_test, y_test)
   1535     if not isinstance(score, numbers.Number):
   1536         raise ValueError("scoring must return a number, got %s (%s) instead."

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/metrics/scorer.pyc in __call__(self, estimator, X, y_true, sample_weight)
     87         else:
     88             return self._sign * self._score_func(y_true, y_pred,
---> 89                                                  **self._kwargs)
     90 
     91 

<ipython-input-39-a8686eb798b2> in overall_average_score(actual, prediction)
      3     recall = precision_recall_fscore_support(actual, prediction, average = 'binary')[1]
      4     f1_score = precision_recall_fscore_support(actual, prediction, average = 'binary')[2]
----> 5     total_score = matthews_corrcoef(actual, prediction)+accuracy_score(actual, prediction)+precision+recall+f1_score
      6     return total_score/5
      7 def show_score(actual,prediction):

/shared/studies/nonregulated/neurostream/neurostream/local/lib/python2.7/site-packages/sklearn/metrics/classification.pyc in matthews_corrcoef(y_true, y_pred)
    395 
    396     if y_type != "binary":
--> 397         raise ValueError("%s is not supported" % y_type)
    398 
    399     lb = LabelEncoder()

ValueError: multiclass is not supported
4

2 に答える 2

3

マシューズ相関係数は -1 と 1 の間のスコアです。したがって、f1_score、precision、recall、accuracy_score、および MCC の平均を計算するのは正しくありません。

MCC 値の意味: 1 は完全な正の相関 0 は相関なし -1 は完全な負の相関

上記の他の評価指標は0から1の間です(最悪から最高の精度指数まで)。範囲と意味は同じではありません。

于 2019-09-23T14:24:25.193 に答える
1

実験を再現しましたが、エラーは発生しません。エラーはベクトルの 1 つを示しているか、actual3prediction つ以上の離散値を含んでいます

外部でトレーニングされたランダム フォレストをスコアリングできるのは、実に奇妙ですGridSearchCV
これを行うために実行する正確なコードを提供していただけますか?

エラーを再現するために使用したコードは次のとおりです。

from sklearn.datasets import make_classification
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import precision_recall_fscore_support, accuracy_score, \
    matthews_corrcoef, make_scorer
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split

def overall_average_score(actual,prediction):
    precision, recall, f1_score, _ = precision_recall_fscore_support(
        actual, prediction, average='binary')
    total_score = (matthews_corrcoef(actual, prediction) +
        accuracy_score(actual, prediction) + precision + recall + f1_score)
    return total_score / 5

grid_scorer = make_scorer(overall_average_score, greater_is_better=True)

print("Without GridSearchCV")
X, y = make_classification(n_samples=500, n_informative=10, n_classes=2)
X_train, X_test, y_train, y_test = train_test_split(X, y,
    test_size=0.5, random_state=0)
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print("Overall average score: ", overall_average_score(y_test, y_pred))

print("-" * 30)
print("With GridSearchCV:")

parameters = {'n_estimators': [10,20,30],
              'max_features': ['auto','sqrt','log2',0.5,0.3], }
gs_rf = GridSearchCV(rf, parameters, cv=5, scoring=grid_scorer)
gs_rf.fit(X_train,y_train)
print("Best score with grid search: ", gs_rf.best_score_)

ここで、提供されたコードについていくつかコメントしたいと思います。

  • random(これは通常はモジュールです) やf1_score(これはメソッドと競合します)などの変数名を使用することはあまりお勧めできませんsklearn.metrics.f1_score
  • 3回呼び出す代わりに、precision直接解凍できます。recallf1_scoreprecision_recall_fscore_support
  • グリッド検索はあまり意味がありません。ツリーが多いほど良いのn_estimatorsです。オーバーフィッティングが心配な場合は、やなどの他のパラメーターを使用して、個々のモデルの複雑さを軽減できます。max_depthmin_samples_split
于 2015-07-25T14:25:58.630 に答える