TypeError when trying to predict labels with argmax

落花浮王杯 提交于 2021-02-08 11:20:25

问题


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!


回答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]


来源:https://stackoverflow.com/questions/62783033/typeerror-when-trying-to-predict-labels-with-argmax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!