user9010401
user9010401

Reputation: 21

AttributeError: 'str' object has no attribute 'mean_validation_score'

This error occurs in my code: AttributeError: 'str' object has no attribute 'mean_validation_score'. What can I do to resolve it?

def report(grid_scores, n_top=3):
    top_scores = sorted(grid_scores, key=itemgetter(1), reverse=True)[:n_top]
    for i, score in enumerate(top_scores):
        print("Rank: {0}".format(i + 1))
        print("Mean validation score: {0:.3f} (std: {1:.3f})".format(
              score.mean_validation_score,
              np.std(score.cv_validation_scores)))
        print("Parameters: {0}".format(score.parameters))
        print("")
report(clf.cv_results_)

Upvotes: 2

Views: 3561

Answers (2)

Ghost
Ghost

Reputation: 1523

You are probably using the grid_search method from the sklearn 0.15-0.17 version to fit RF args, which was long ago deprecated. The new method for the scores is not even grid_scores_, but cv_results_.

Check this link: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html

And replace the statistic mean_validation_score with the one better for your args sweep.

Or if you want just a complete summary, forget of calling report() just do a pd.DataFrame(random_search.cv_results_), sort by rank_test_score and that's it.

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51683

The error is quite clear: AttributeError: 'str' object has no attribute 'mean_validation_score'

There is only one place you use mean_validation_score and the object you use it on is a string - not what you think it is. string does not support the method you use on it - hence the error:

    for i, score in enumerate(top_scores):                              # score from here
        print("Rank: {0}".format(i + 1))
        print("Mean validation score: {0:.3f} (std: {1:.3f})".format(
              score.mean_validation_score,                              # usage here
              np.std(score.cv_validation_scores)))

Obviosly the top_scores is a iterable of type string - hence when you enumerate it

for i, score in enumerate(top_scores):

it produces indexes i and strings score.

You can resolve it by debugging your code:

top_scores = sorted(grid_scores, key=itemgetter(1), reverse=True)[:n_top]

and see why there are strings in it - fix that so it contains the objects that have .mean_validation_score and the error vanishes.


Helpful:

Upvotes: 3

Related Questions