我对编码很陌生,尤其是Python。我正在尝试使用 PyCharm 中的脚本中的 Teachable Machines 对象识别器,但我不断收到错误。此代码的目的是获取图像,然后根据模型打印该对象的置信度分数。我已经下载了模型和标签文件,并将它们放在与脚本相同的文件夹中。我相信我已经下载了所有必需的软件包,Tensorflow、NumPy、Pillow、Keras。不确定这是否重要,但我在 Windows 上。
这是代码,我直接从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}.
遇到异常:无法识别的关键字参数传递给 DepthwiseConv2D:{'groups':1}
感谢任何和所有帮助! 谢谢你
是的...我也得到了这个答案。 您需要构建一个自定义加载程序 - 这应该会有所帮助。
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}")