Reputation: 21
I am trying to use the Teachable Machines object recognizer from a script in PyCharm, but I keep getting an error. The purpose of this code is to take in an image, and then print what the object is with a confidence score, based on the model. I have downloaded the model and label files and have put them in the same folder as the script. I believe I have downloaded all of the necessary packages, Tensorflow, NumPy, Pillow, Keras. Not sure if it matters, but I am on windows.
This is the code, I copied it directly from Teachable Machine:
from keras.models import load_model # TensorFlow is required for Keras to work
from PIL import Image, ImageOps # Install pillow instead of PIL
import numpy as np
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
model = load_model("keras_Model.h5", compile=False)
# Load the labels
class_names = open("labels.txt", "r").readlines()
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
image = Image.open("<IMAGE_PATH>").convert("RGB")
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
# Load the image into the array
data[0] = normalized_image_array
# Predicts the model
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
# Print prediction and confidence score
print("Class:", class_name[2:], end="")
print("Confidence Score:", confidence_score)
I have replaced the "IMAGE_PATH" with the path to an image. I get the following as an error:
Traceback (most recent call last):
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\ops\operation.py", line 208, in from_config
return cls(**config)
^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\layers\convolutional\depthwise_conv2d.py", line 118, in __init__
super().__init__(
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\layers\convolutional\base_depthwise_conv.py", line 106, in __init__
super().__init__(
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\layers\layer.py", line 264, in __init__
raise ValueError(
ValueError: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\olive\Downloads\pythonProject2\TESTER.py", line 9, in <module>
model = load_model("keras_model.h5", compile=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\saving\saving_api.py", line 183, in load_model
return legacy_h5_format.load_model_from_hdf5(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\legacy_h5_format.py", line 133, in load_model_from_hdf5
model = saving_utils.model_from_config(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\saving_utils.py", line 85, in model_from_config
return serialization.deserialize_keras_object(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\serialization.py", line 495, in deserialize_keras_object
deserialized_obj = cls.from_config(
^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\models\sequential.py", line 333, in from_config
layer = saving_utils.model_from_config(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\saving_utils.py", line 85, in model_from_config
return serialization.deserialize_keras_object(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\serialization.py", line 495, in deserialize_keras_object
deserialized_obj = cls.from_config(
^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\models\sequential.py", line 333, in from_config
layer = saving_utils.model_from_config(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\saving_utils.py", line 85, in model_from_config
return serialization.deserialize_keras_object(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\serialization.py", line 495, in deserialize_keras_object
deserialized_obj = cls.from_config(
^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\models\model.py", line 517, in from_config
return functional_from_config(
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\models\functional.py", line 517, in functional_from_config
process_layer(layer_data)
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\models\functional.py", line 497, in process_layer
layer = saving_utils.model_from_config(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\saving_utils.py", line 85, in model_from_config
return serialization.deserialize_keras_object(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\legacy\saving\serialization.py", line 504, in deserialize_keras_object
deserialized_obj = cls.from_config(cls_config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\olive\Downloads\pythonProject2\.venv\Lib\site-packages\keras\src\ops\operation.py", line 210, in from_config
raise TypeError(
TypeError: Error when deserializing class 'DepthwiseConv2D' using config={'name': 'expanded_conv_depthwise', 'trainable': True, 'dtype': 'float32', 'kernel_size': [3, 3], 'strides': [1, 1], 'padding': 'same', 'data_format': 'channels_last', 'dilation_rate': [1, 1], 'groups': 1, 'activation': 'linear', 'use_bias': False, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, 'depth_multiplier': 1, 'depthwise_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1, 'mode': 'fan_avg', 'distribution': 'uniform', 'seed': None}}, 'depthwise_regularizer': None, 'depthwise_constraint': None}.
Exception encountered: Unrecognized keyword arguments passed to DepthwiseConv2D: {'groups': 1}
Upvotes: 2
Views: 162
Reputation: 1
Yeah... I got this answer too. You need to build a custom loader - this should help.
import tensorflow as tf
from keras.layers import DepthwiseConv2D
from keras.models import load_model
import cv2
import numpy as np
# Define a custom DepthwiseConv2D class without the groups parameter
class CustomDepthwiseConv2D(DepthwiseConv2D):
def __init__(self, **kwargs):
# Remove the 'groups' parameter if it exists
if 'groups' in kwargs:
del kwargs['groups'] # Remove the groups parameter
super().__init__(**kwargs)
# Create a dictionary of custom objects to pass to the load_model function
custom_objects = {
'DepthwiseConv2D': CustomDepthwiseConv2D,
}
# Load the model with the custom object
try:
model = load_model("keras_model.h5", custom_objects=custom_objects,
compile=False)
print("Model loaded successfully.")
except Exception as e:
print(f"Error loading model: {e}")
Upvotes: 0