0

I have successfully followed this transfer learning tutorial to make my own classifier with two classes, "impressionism" and "modernism".

Now trying to get a label for my test image, applying advice from this thread:

y_prob = model.predict(new_image)
y_prob

(gives this output) array([[3.1922062e-04, 9.9968076e-01]], dtype=float32)

y_classes = y_prob.argmax(axis=-1)
y_classes
(gives this output) array([1])

# create a list containing the class labels
labels = ['modernism', 'impressionism']
predicted_label = sorted(labels)[y_classes]

Results in error:

"TypeError                                 Traceback (most recent call last)
<ipython-input-35-571175bcfc65> in <module>()
      1 # create a list containing the class labels
      2 labels = ['modernism', 'impressionism']
----> 3 predicted_label = sorted(labels)[y_classes]

TypeError: only integer scalar arrays can be converted to a scalar index"

What am I doing wrong and what would be the right way to access the text labels (and their probabilities) for my test image? If I understand the array prediction, it has recognized from my image folders that there are two classes.

Many thanks if you have time to help!

vjuss
  • 199
  • 1
  • 10

1 Answers1

1

What's happening here is that y_prob.argmax(axis=-1) is returning an array value of [1]. Only numpy arrays can index/splice with a list.

The issue occurs due to the sorted method, I was not accounting for that in my testing. Even though the input array is type np.ndarray, the output becomes a list.

So either:

labels = ['modernism', 'impressionism']
predicted_label = numpy.array(sorted(labels))[y_classes]

or

labels = numpy.array(['modernism', 'impressionism'])
labels.sort()
predicted_label = labels[y_classes]
M Z
  • 4,571
  • 2
  • 13
  • 27
  • Thank you for your quick answer! I now have `labels = np.array(['modernism', 'impressionism']) predicted_label = sorted(labels)[y_classes]` but, weirdly enough, I get the same error. Sorted was based on Guillame's advice: "If you have a list of labels called labels, the predicted label name will be: `predicted_label = sorted(labels)[y_classes]`" – vjuss Jul 07 '20 at 20:42
  • This was it! Thank you so much, I was stuck with this for long. Now I get this output `array(['modernism'], dtype=' – vjuss Jul 07 '20 at 21:22
  • 1
    you can do `print(y_prob.max(axis=-1))` and that will print the confidence of the positive class. – M Z Jul 07 '20 at 21:33
  • Perfect, this helps a lot! Thanks. – vjuss Jul 07 '20 at 21:37