Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load_model() missing 1 required positional argument: 'filepath'

Been following a few guides on Tensorflow and Keras, new to python, came from c++. Having an issue saying "load_model() missing 1 required positional argument: 'filepath'"

heres my code:

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])
like image 888
jrcrash Avatar asked Oct 18 '25 11:10

jrcrash


1 Answers

TL;DR The fix is to not specify the filepath as a keyword parameter:

model = load_model('Image_Classifier.h5')

Longer Explanation:

I think the reason is that filepath is being treated as a positional argument instead of a keyword argument (see the parameter entry in the glossary for explanations of these). If you look at the load_model function itself this is confusing, because the signature is:

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

Here filepath is a positional-or-keyword argument - you can either just pass the filename in the first position or do what you did and say filepath='Image_Classifier.h5'. BUT, there is some more machinery in place that complicates it. The error I receive when I run your code is

    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'

Note the load_model function is not being called directly, it is going through this load_wrapper function with signature

def load_wrapper(*args, **kwargs)

The function signature allows for an arbitrary number of positional arguments followed by an arbitrary number of keyword arguments. That function then seems to do some processing of what was passed in to find keyword args, and my guess is if you pass filepath as a keyword parameter, it then doesn't have anything to pass for *args, even though the load_model function expects exactly one thing to be passed through the positional *args.

The end result is filepath gets treated as a positional-only argument, and you must pass the value directly without specifying it as a keyword argument.

like image 187
adamconkey Avatar answered Oct 20 '25 02:10

adamconkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!