1

I have successfully followed this official tutorial on image classification with transfer learning: https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub

My experimental model is now saved and supposed to recognize when it sees a "good" painting. However, I want to test this with an image that the model has not seen before. So far I have only used notebooks where the dataset is already divided into train and test folders. However, this is not the case here.

I assume I need something like

img = tf.keras.preprocessing.image.load_img("/content/mytestimage.jpeg", target_size=(224,224))

among other things; however, for a beginner it would be useful to see an example of this kind of test prediction. So far I have searched without results - if anyone has any advice I'm super happy to hear!

vjuss
  • 199
  • 1
  • 10

1 Answers1

1

Here's how to do it with mobilenet transfer learning with keras but most of the code should be the same. A full transfer learning tutorial can be found here. I found it very useful.

from PIL import Image
from tensorflow.keras.models import load_model

model = load_model('path/to/model.h5')

img = Image.open(file)
array = np.asarray(img, dtype=np.float32)
  arrayexp = np.expand_dims(array, axis=0)
  arrayexp = (arrayexp/127)-1 #This is a normalization factor specifically for Mobilenet but I think it's used for many other networks
result = model.predict(arrayexp)
  print(np.argmax(result)) #Prints class with highest confidence
  print(result[0][np.argmax(result)]) #Prints confidence for the highest

theastronomist
  • 955
  • 2
  • 13
  • 33
  • Perfect, seems really helpful. Thank you so much! – vjuss Jul 07 '20 at 15:21
  • 1
    You're welcome. Could you mark it as the correct answer if it works? – theastronomist Jul 07 '20 at 15:28
  • 1
    For sure! Right now I have added your suggestion to the end of my notebook, model being `model = load_model("/content/gdrive/My Drive/Colab Notebooks/TF_hub_transfer/1594130083/saved_model.pb")` It guess it does not like pb format? `OSError: SavedModel file does not exist at: /content/gdrive/My Drive/Colab Notebooks/TF_hub_transfer/1594130083/saved_model.pb/{saved_model.pbtxt|saved_model.pb}` The model exists, I have checked that :) – vjuss Jul 07 '20 at 16:42
  • I now tried the Keras tutorial you linked (instead of TF Hub). It works smoothly! However the prediction of my test image is in array format `array([[3.1922062e-04, 9.9968076e-01]], dtype=float32)` I wonder if you were able to decode the results into classes? – vjuss Jul 07 '20 at 18:28
  • Update: I made a separate question about decoding and it was solved: https://stackoverflow.com/questions/62783033/typeerror-when-trying-to-predict-labels-with-argmax – vjuss Jul 07 '20 at 21:33