加载 keras 模型时出现 ValueError: ('无法识别的关键字参数:', dict_keys(['ragged']))

问题描述 投票:0回答:5

我正在尝试使用下面的代码片段加载 keras 模型:

    from tensorflow import keras
    from PIL import Image, ImageOps
    import numpy as np

    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)

    # Load the model
    model = keras.models.load_model('keras_model.h5')

    # 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("YES/1.jpg")

    #resize the image to a 224x224 with the same strategy as in TM2:
    #resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    #turn the image into a numpy array
    image_array = np.asarray(image)

    # display the resized image
    image.show()

    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

    # Load the image into the array
    data[0] = normalized_image_array

    # run the inference
    prediction = model.predict(data)
    print(prediction)

当我执行上面的代码时,出现以下错误:

文件“C:\ProgramData\Anaconda3\lib\site-packages ensorflow\python\keras ngine ase_layer.py”, 第 446 行,在 from_config 中 返回 cls(**配置)

文件“C:\ProgramData\Anaconda3\lib\site-packages ensorflow\python\keras ngine\input_layer.py”, 第 80 行,在 init 中 raise ValueError('无法识别的关键字参数:', kwargs.keys())

ValueError: ('无法识别的关键字参数:', dict_keys(['ragged']))

python tensorflow keras
5个回答
4
投票

只是添加贾斯汀已经提到的内容。当我尝试在安装了 TensorFlow 1.15 的环境中使用使用 TensorFlow 2.3.1 训练的模型运行推理脚本时,遇到了此问题。


2
投票

您应该按照以下要求运行它

keras==2.2.4 张量流==1.15.0 枕头==7.0.0


2
投票

训练模型和加载模型时检查tf的版本。两者应该是相同的版本,否则可能会出现此类错误。我在 google colab 上遇到了同样的问题,我正在训练在最新 tf 版本上运行的模型,而我尝试加载该模型的机器中的 tf 版本不同。因此,在导入 tf 之前,我在 google colab 中安装了相同版本的 tf。它就像一个魅力。


1
投票

在tensorflow==2.5.0中,在我的例子中,我在2.5.0上训练了模型,并尝试在tensorflow==1.11和1.15上运行.h5模型的infrence。和 2.1.0,但由于这个额外的层在之前的版本中不存在。 https://www.tensorflow.org/versions/r2.5/api_docs/python/tf/keras/layers/experimental/preprocessing/Rescaling

该层在早期版本的tensorflow中不存在。

我发现的另一个问题是,现在 conv-2d 层中有一个“groups”关键字,这在以前版本的 TensorFlow 中是不存在的。


0
投票

如果您不知道哪些版本兼容。打开Google Colab,检查keras和tensorflow的版本如下。

import keras
import tensorflow
print(keras.__version__)
print(tensorflow.__version__)

对我来说,两者都是 2.15.0 版本。然后我在我的电脑上的项目中使用了相同的版本。我的问题解决了。

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