python - load_model() 缺少 1 个必需的位置参数 : 'filepath'

标签 python tensorflow keras

一直在关注 Tensorflow 和 Keras 的一些指南,对 python 是新手,来自 c++。遇到问题说“load_model() 缺少 1 个必需的位置参数:'filepath'”

这是我的代码:

from keras.datasets import cifar10
import keras.utils as utils
from keras.models import load_model
import numpy as np

labelsArray = ["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"]

(_, _), (testImages, testLabels) = cifar10.load_data()

testImages = testImages.astype('float32') / 255.0
testLabels = utils.to_categorical(testLabels)

model = load_model(filepath='Image_Classifier.h5')

results = model.evaluate(x=testImages, y=testLabels)
print("Train loss:", results[0])
print("Test Accuracy:", results[1])

最佳答案

TL;DR 解决方法是不将文件路径指定为关键字参数:

model = load_model('Image_Classifier.h5')

更长的解释:

我认为原因是 filepath 被视为位置参数而不是关键字参数(有关这些的解释,请参阅 the glossary 中的 parameter 条目) .如果您查看 load_model函数本身这是令人困惑的,因为签名是:

def load_model(filepath, custom_objects=None, compile=True)

这里 filepath 是一个位置或关键字参数 - 你可以只在第一个位置传递文件名,或者做你所做的并说 filepath='Image_Classifier.h5'。但是,有更多的机器使它复杂化。我在运行您的代码时收到的错误是

    model = load_model(filepath='Image_Classifier.h5')
File "/Users/adam/.miniconda3/envs/tf/lib/python3.7/site-packages/keras/engine/saving.py", line 492, in load_wrapper
    return load_function(*args, **kwargs)
TypeError: load_model() missing 1 required positional argument: 'filepath'

请注意,load_model 函数并未被直接调用,而是通过 load_wrapper 调用带签名的函数

def load_wrapper(*args, **kwargs)

函数签名允许任意数量的位置参数后跟任意数量的关键字参数。然后该函数似乎对传入的内容进行一些处理以查找关键字参数,我的猜测是如果您将 filepath 作为关键字参数传递,那么它就没有任何内容可以传递给 *args,即使 load_model 函数期望通过位置 *args 传递一件事。

最终结果是 filepath 被视为仅位置参数,您必须直接传递值而不将其指定为关键字参数。

关于python - load_model() 缺少 1 个必需的位置参数 : 'filepath' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112631/

相关文章:

python - 为什么对 tensorflow 张量进行 pickle 会失败?

python - 无法删除 TypeError : unhashable type: 'numpy.ndarray'

python - 如何在 tensorflow 数据集的每次迭代中添加随机性?

python - 使用不同的人工神经网络框架(ffnet、tensorflow)复制结果

python - 在Keras中实现因果CNN以进行多元时间序列预测

python - 警告 :tensorflow:Model was constructed with shape (None, ....)

python - Pandas:在条件后创建指示列

python - 指定文件名路径时出现问题

python - 如何根据条件合并两个不同大小的 Pandas DataFrame

python - 集合文字给出了与集合函数调用不同的结果