31

Trying to run a trained keras model with the following python code:

from keras.preprocessing.image import img_to_array
from keras.models import load_model

from imutils.video import VideoStream
from threading import Thread
import numpy as np
import imutils
import time
import cv2
import os

MODEL_PATH = "/home/pi/Documents/converted_keras/keras_model.h5"

print("[info] loading model..")
model = load_model(MODEL_PATH)


print("[info] starting vid stream..")
vs = VideoStream(usePiCamera=True).start()
time.sleep(2.0)

while True:
    frame = vs.Read()
    frame = imutils.resize(frame, width=400)

    image = cv2.resize(frame, (28, 28))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    (fuel, redBall, whiteBall, none) = model.predict(image)[0]
    label = "none"
    proba = none

    if fuel > none and fuel > redBall and fuel > whiteBall:
        label = "Fuel"
        proba = fuel
    elif redBall > none and redBall > fuel and redBall > whiteBall:
        label = "Red Ball"
        proba = redBall
    elif whiteBall > none and whiteBall > redBall and whiteBall > fuel:
        label = "white ball"
        proba = whiteBall
    else:
        label = "none"
        proba = none

    label = "{}:{:.2f%}".format(label, proba * 100)
    frame = cv2.putText(frame, label, (10, 25),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

print("[info] cleaning up..")
cv2.destroyAllWindows()
vs.stop()

When I run it with python3, I get the following error: TypeError: __init__() got an unexpected keyword argument 'ragged'

What's causing the error, and how do I get around it?

Versions: Keras v2.3.1 tensorflow v1.13.1

Edit to add:

Traceback (most recent call last):
  File "/home/pi/Documents/converted_keras/keras-script.py", line 18, in <module>
    model = load_model(MODEL_PATH)
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/saving.py", line 492, in load_wrapper
    return load_function(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/saving.py", line 584, in load_model
    model = _deserialize_model(h5dict, custom_objects, compile)
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/saving.py", line 274, in _deserialize_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/saving.py", line 627, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "/usr/local/lib/python3.7/dist-packages/keras/layers/__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "/usr/local/lib/python3.7/dist-packages/keras/utils/generic_utils.py", line 147, in deserialize_keras_object
    list(custom_objects.items())))
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/sequential.py", line 301, in from_config
    custom_objects=custom_objects)
  File "/usr/local/lib/python3.7/dist-packages/keras/layers/__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "/usr/local/lib/python3.7/dist-packages/keras/utils/generic_utils.py", line 147, in deserialize_keras_object
    list(custom_objects.items())))
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/sequential.py", line 301, in from_config
    custom_objects=custom_objects)
  File "/usr/local/lib/python3.7/dist-packages/keras/layers/__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "/usr/local/lib/python3.7/dist-packages/keras/utils/generic_utils.py", line 147, in deserialize_keras_object
    list(custom_objects.items())))
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/network.py", line 1056, in from_config
    process_layer(layer_data)
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/network.py", line 1042, in process_layer
    custom_objects=custom_objects)
  File "/usr/local/lib/python3.7/dist-packages/keras/layers/__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "/usr/local/lib/python3.7/dist-packages/keras/utils/generic_utils.py", line 149, in deserialize_keras_object
    return cls.from_config(config['config'])
  File "/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py", line 1179, in from_config
    return cls(**config)
  File "/usr/local/lib/python3.7/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'ragged'

h5 file link (google drive)

zxsq
  • 313
  • 1
  • 3
  • 6
  • Please add your full error stack trace, along with part of code where you are getting error. – Vivek Mehta Nov 15 '19 at 13:56
  • @VivekMehta I have added the full code and the error trace, I think this is what you asked for? Not that sure, sorry. – zxsq Nov 15 '19 at 14:08
  • `"/home/pi/Documents/converted_keras/keras_model.h5"` is this the full path? Try giving it the absolute path. – DUDANF Nov 15 '19 at 14:08
  • @daudnadeem Yes, that's the absolute path to it. – zxsq Nov 15 '19 at 14:13
  • Thanks for adding the full code and stack trace. It looks like something in generic_utils is being called with an __init__( ragged='something') but not sure why that would happen. – rajah9 Nov 15 '19 at 14:14
  • @zxsq can you give me a sample h5 file, or a link to one, so I can reproduce? – DUDANF Nov 15 '19 at 14:19
  • [link to the h5 file](https://drive.google.com/file/d/1-8ADI40ujjmcLpv-Shn9b5qhvIZNqYcn/view?usp=sharing) – zxsq Nov 15 '19 at 14:25
  • @zxsq seems like your issue is in your h5 file. I found 'ragged' in the h5, and deleted that key:value, after which I get `OSError: Unable to open file (file signature not found)` error. Possible corrupted h5 file? – DUDANF Nov 15 '19 at 14:31
  • @daudnadeem hmm, not sure. I made it with teachable machine, so I'll give it a go making another one but, I don't think it would be that. – zxsq Nov 15 '19 at 14:38
  • How did you produce that model file? With which keras version? – Dr. Snoopy Nov 15 '19 at 14:47
  • @MatiasValdenegro It was exported from [teachable machine](https://teachablemachine.withgoogle.com/) as keras – zxsq Nov 15 '19 at 15:00

2 Answers2

68

So I tried link above which you have mentioned teachable machine
As it turns out model you have exported is from tensorflow.keras and not directly from keras API. These two are different. So while loading it might be using tf.ragged tensors that might not be compatible with keras API.

Soulution to your issue:

Don't import keras directly as your model is saved with Tensorflow's keras high level api. Change all your imports to tensorflow.keras

Change:

from keras.preprocessing.image import img_to_array
from keras.models import load_model

to this:

from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model

It will solve your issue.

EDIT :
All of your imports, either should be from Keras or tensorflow.keras. Although being same API few things are different which creates these kind of issues. Also for tensorflow backend tf.keras is preferred, because Keras 2.3.0 is last major release which will support backends other than tensorflow.

This release brings the API in sync with the tf.keras API as of TensorFlow 2.0. However note that it does not support most TensorFlow 2.0 features, in particular eager execution. If you need these features, use tf.keras. This is also the last major release of multi-backend Keras. Going forward, we recommend that users consider switching their Keras code to tf.keras in TensorFlow 2.0.

Vivek Mehta
  • 2,612
  • 2
  • 18
  • 30
  • This fixed my issue. Thank you so much :) – Manthan_Admane Mar 28 '20 at 15:31
  • 1
    I just change `import keras` by `import tensorflow.keras as keras`, and it worked! Thank you. – Chau Pham Jul 14 '20 at 23:55
  • I encountered the same problem. However, I can't use `tf.keras` because I'm trying to run keras with a different backend. I trained & saved my model using `tf 2.2.0` & `keras 2.3.0-tf`, and trying to run it on `keras 2.2.4`, backend `PlaidML`. Any possible solution? Or just theoretically impossible? – Kirk Mar 02 '21 at 16:46
2

Like @Vivek Mehta said, first change load_model from keras to tensorflow.keras i.e

from tensorflow.keras.models import load_model

But even then if the model loading shows error like KeyError: 'sample_weight_mode' then do the following

from tensorflow.keras.models import load_model

model = load_model('model.h5', compile = False)
Hemanth Kollipara
  • 902
  • 11
  • 16