可示教机器 Keras 模型加载问题

问题描述 投票:0回答:1
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("/chest_xray/val/PNEUMONIA/person1_virus_9.jpeg").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)

我正在尝试加载我在本地设备上使用 Teachable Machine 网站训练过的 keras 模型,并且我也从该网站复制了代码。但是,当我尝试加载模型时,出现以下错误。

    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}

我认为问题是由于一些不兼容的tensorflow和keras包造成的,但我已经检查过,这似乎没问题。这是我安装的版本。

keras==3.2.1 张量流==2.16.1

我尝试安装各种不同的版本来解决这个问题,但我仍然面临同样的问题。

tensorflow keras teachable-machine
1个回答
0
投票

查看您提供的解决方案后,我仍然无法纠正错误。我正在使用 OpenCV keras 代码,但没有找到解决方案。

from keras.models import load_model # Keras 需要 TensorFlow 才能工作 import cv2 # 安装 opencv-python 将 numpy 导入为 np

为了清晰起见,禁用科学记数法

np.set_printoptions(抑制=真)

加载模型

model = load_model("keras_Model.h5",compile=False)

加载标签

class_names = open("labels.txt", "r").readlines()

CAMERA 可以是 0 或 1,具体取决于您计算机的默认摄像头

相机 = cv2.VideoCapture(0)

虽然正确: # 抓取网络摄像头的图像。 ret,图像=camera.read()

# Resize the raw image into (224-height,224-width) pixels
image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)

# Show the image in a window
cv2.imshow("Webcam Image", image)

# Make the image a numpy array and reshape it to the models input shape.
image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)

# Normalize the image array
image = (image / 127.5) - 1

# Predicts the model
prediction = model.predict(image)
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:", str(np.round(confidence_score * 100))[:-2], "%")

# Listen to the keyboard for presses.
keyboard_input = cv2.waitKey(1)

# 27 is the ASCII for the esc key on your keyboard.
if keyboard_input == 27:
    break

相机.release() cv2.destroyAllWindows()

© www.soinside.com 2019 - 2024. All rights reserved.