2

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_)
DollarAkshay
  • 2,024
  • 1
  • 19
  • 37
user9010401
  • 21
  • 1
  • 5

1 Answers1

4

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:

Patrick Artner
  • 48,339
  • 8
  • 43
  • 63