Unable to load .h5 file made in Google Colab to Jupyter Notebook [duplicate]

∥☆過路亽.° 提交于 2021-02-10 14:16:25

问题


I tried a code for Face mask detect and alert system and I am getting an error regarding the same. I trained the model in Google Collaboratory and ran the following code in Jupyter Notebook. The code is as follows:

# Import necessary libraries
from keras.models import load_model
import cv2
import numpy as np
import tkinter
from tkinter import messagebox
import smtplib

# Initialize Tkinter
root = tkinter.Tk()
root.withdraw()

#Load trained deep learning model
model = load_model('face_mask_detection_alert_system.h5')

#Classifier to detect face
face_det_classifier=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Capture Video
vid_source=cv2.VideoCapture(0)

# Dictionaries containing details of Wearing Mask and Color of rectangle around face. If wearing mask 
then color would be 
# green and if not wearing mask then color of rectangle around face would be red
text_dict={0:'Mask ON',1:'No Mask'}
rect_color_dict={0:(0,255,0),1:(0,0,255)}

SUBJECT = "Subject"   
TEXT = "One Visitor violated Face Mask Policy. See in the camera to recognize user. A Person has been 
detected without a face mask in the Hotel Lobby Area 9. Please Alert the authorities."


# While Loop to continuously detect camera feed
    while(True):

        ret, img = vid_source.read()
        grayscale_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces = face_det_classifier.detectMultiScale(grayscale_img,1.3,5)  

        for (x,y,w,h) in faces:

            face_img = grayscale_img[y:y+w,x:x+w]
            resized_img = cv2.resize(face_img,(56,56))
            normalized_img = resized_img/255.0
            reshaped_img = np.reshape(normalized_img,(1,56,56,1))
            result=model.predict(reshaped_img)

            label=np.argmax(result,axis=1)[0]
  
            cv2.rectangle(img,(x,y),(x+w,y+h),rect_color_dict[label],2)
            cv2.rectangle(img,(x,y-40),(x+w,y),rect_color_dict[label],-1)
            cv2.putText(img, text_dict[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,0),2) 
    
            # If label = 1 then it means wearing No Mask and 0 means wearing Mask
            if (label == 1):
                # Throw a Warning Message to tell user to wear a mask if not wearing one. This will 
                stay
                #open and No Access will be given He/She wears the mask
                messagebox.showwarning("Warning","Access Denied. Please wear a Face Mask")
        
                # Send an email to the administrator if access denied/user not wearing face mask 
                message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
                mail = smtplib.SMTP('smtp.gmail.com', 587)
                mail.ehlo()
                mail.starttls()
                mail.login('aaaa@gmail.com','bbbb@gmail.com')
                mail.sendmail('aaaa@gmail.com','aaaa@gmail.com',message)
                mail.close
            else:
                pass
                break

    cv2.imshow('LIVE Video Feed',img)
    key=cv2.waitKey(1)

    if(key==27):
        break
    
cv2.destroyAllWindows()
source.release()

Error:

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Users\IZZY\Desktop\Dataset\facemaskalert_2.py", line 14, in <module>
    model = load_model('face_mask_detection_alert_system.h5')
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\saving.py", line 492, in load_wrapper
    return load_function(*args, **kwargs)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\saving.py", line 584, in load_model
    model = _deserialize_model(h5dict, custom_objects, compile)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\saving.py", line 274, in _deserialize_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\saving.py", line 627, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\layers\__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\utils\generic_utils.py", line 147, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\sequential.py", line 301, in from_config
    custom_objects=custom_objects)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\layers\__init__.py", line 168, in deserialize
    printable_module_name='layer')
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\utils\generic_utils.py", line 149, in deserialize_keras_object
    return cls.from_config(config['config'])
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\engine\base_layer.py", line 1179, in from_config
    return cls(**config)
  File "C:\Users\IZZY\AppData\Local\Programs\Python\Python37\lib\site- 
  packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  TypeError: __init__() got an unexpected keyword argument 'ragged'

Source Code : https://theaiuniversity.com/courses/face-mask-detection-alert-system/

Methods Tried but did not help : Unexpected keyword argument 'ragged' in Keras

EDIT:-h5 FILE https://drive.google.com/file/d/10oHrqtrYoD2Hx0olLnnf0qYSQLlrt3Kq/view?usp=sharing.


回答1:


Seems the issue is similar as mentioned in this stackoverflow question. already.

As the accepted answer here mentions that the exported model may be from tf.keras and not keras directly :

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

My suggestion:

1.You should try to use tf.keras for all keras imports

  1. And also as Mohammad mentions in the answer , use compile=False in load_model.

  2. Check the version of tf and keras in colab and local environment.Both versions need to be same.

From Keras github issues regarding this.




回答2:


I think the version of TensorFlow that you used to train and save your model is different than the one that you are using to load the model.

Try compile=False while loading your model:

#Load trained deep learning model
model = load_model('face_mask_detection_alert_system.h5', compile=False)


来源:https://stackoverflow.com/questions/65346324/unable-to-load-h5-file-made-in-google-colab-to-jupyter-notebook

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