【问题标题】:Unable to load .h5 file made in Google Colab to Jupyter Notebook [duplicate]无法将 Google Colab 中制作的 .h5 文件加载到 Jupyter Notebook [重复]
【发布时间】:2023-03-14 19:40:01
【问题描述】:

我尝试了面罩检测和警报系统的代码,但我收到了同样的错误。我在 Google Collaboratory 中训练了模型,并在 Jupyter Notebook 中运行了以下代码。代码如下:

# 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()

错误:

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'

源代码:https://theaiuniversity.com/courses/face-mask-detection-alert-system/

方法尝试但没有帮助:Unexpected keyword argument 'ragged' in Keras

编辑:-h5 文件 https://drive.google.com/file/d/10oHrqtrYoD2Hx0olLnnf0qYSQLlrt3Kq/view?usp=sharing.

【问题讨论】:

    标签: python tensorflow keras jupyter-notebook google-colaboratory


    【解决方案1】:

    我认为您用于训练和保存模型的 TensorFlow 版本与您用于加载模型的版本不同。

    在加载模型时尝试compile=False

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

    【讨论】:

    • 我采纳了你的建议,现在又遇到了另一个错误:- TypeError: ('Keyword argument not understand:', 'groups')
    【解决方案2】:

    似乎问题与* question. 中提到的类似。

    正如此处接受的答案提到导出的模型可能来自 tf.keras 而不是直接来自 keras:

    "不要直接导入 keras,因为你的模型是用 Tensorflow 保存的 keras 高级 API。将所有导入更改为 tensorflow.keras"。

    我的建议:

    1.您应该尝试将 tf.keras 用于所有 keras 导入

    1. 正如 Mohammad 在回答中提到的,在 load_model 中使用 compile=False

    2. 在colab和本地环境中查看tf和keras的版本。两个版本需要相同。

    来自Keras github 关于此的问题。

    【讨论】:

    • TypeError: ('Keyword argument not understand:', 'groups') 我现在收到此错误
    • 嗨 Daigo ,似乎这是一个 tf 和 keras 版本不匹配的问题,正如这个(*.com/questions/63308383/…)* 问题中所指出的那样。必要时使用 pip install --upgrade tensorflow 和 pip install --upgrade keras 进行升级