user13641081
user13641081

Reputation:

How do I load multiple already saved models

I trained 5 different classifiers and save to disk, like so:

for e in range(len(ensemble)):       #..ensemble: -list of 5 models
        save_file = "Model_" + str(e) + ".h5"
        ensemble[e].save(save_file)
        print("MODEL ", e, " SAVED!") 

So that I have five models, one for each classifier:

$ls
accuracy.txt  dfObj.csv  Model_0.h5  Model_1.h5  Model_2.h5  
Model_3.h5  Model_4.h5  predicted_label.csv  real_label.csv

I would like to evaluate these classifiers on new unseen dataset, so there's need to load them. So I tried this:

import os
from keras.models import load_model    
ensemble = []
for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith('.h5'):
                    model = load_model(file)
                    ensemble.append(model)
                    

Which generates the error:

 raise IOError("SavedModel file does not exist at: %s/{%s|%s}" %
OSError: SavedModel file does not exist at: Model_4.h5/{saved_model.pbtxt|saved_model.pb}

Can someone point how to load these models back for evaluation on unseen dataset?

Upvotes: 0

Views: 519

Answers (1)

Nikaido
Nikaido

Reputation: 4629

That's because you are loading from the wrong path

the files that you are iterating from the files list are relative paths

there an example:

import os
model.save('/tmp/test.h5')
for root, dirs, files in os.walk('/tmp/'):
  print(root) # root path 'tmp'
  for file in files:
    print(file) # relative path 'test.h5'
    keras.models.load_model(file) # error relative path

loading from absolute path works:

keras.models.load_model('/tmp/test.h5')

This should be the correct way to load the absolute paths:

# !/usr/bin/python3
import os

for root, dirs, files in os.walk(your_path, topdown = False):
   for name in files:
      print(os.path.join(root, name))
   for name in dirs:
      print(os.path.join(root, name))

details of os.walk here

Upvotes: 1

Related Questions