How to interpret output of model.predict() in Keras

Viewed 265

I have a problem with my code when i try to excute predict an image . using keras etc.

I am looking for ways on how to output the array

for example [1,0,0] and then output rock

import numpy as np
from google.colab import files
from keras.preprocessing import image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.applications.vgg16 import VGG16

%matplotlib inline

uploaded = files.upload()

for fn in uploaded.keys():
 
  # predicting images
  path = fn
  img = image.load_img(path, target_size=(150,150))
  imgplot = plt.imshow(img)
  x = image.img_to_array(img)
  x = np.expand_dims(x, axis=0)
  x = preprocess_input(x)

  #images = np.vstack([x])
  classes = model.predict(x, batch_size=10)
  print(classes)

  print(fn)
  if classes==[[1,0,0]]:
    print('paper')
  else:
    print('rock')

and then the output like this

Saving 0a3UtNzl5Ll3sq8K.png to 0a3UtNzl5Ll3sq8K (4).png
[[1. 0. 0.]]
0a3UtNzl5Ll3sq8K.png
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-69-863494647f7a> in <module>()
     28 
     29   print(fn)
---> 30   if classes==[[1,0,0]]:
     31     print('paper')
     32   else:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Screenshoot program: enter image description here

1 Answers

Always check the type of the objects you are working with.

The return type is a tensor array, not a list; it's practically an array of probabilities for each label. In order to transform it into a numpy array you need to use prediction.numpy().

In your case, the confusion comes from the fact that by chance the first label does have a probability of 100% and the rest of 0%.

In addition to this, pay attention to the way you compare:

[[1. 0. 0.]] with [[1,0,0]]

You need to use the argmax() in order to correctly get a label.

Related