0
votes

I trained a number image and made a model file.

The corresponding sauce is as follows.

import os
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical 
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense 
from tensorflow.keras.models import load_model
import cv2
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Flatten, Convolution2D, MaxPooling2D
from tensorflow.keras.layers import Dropout, Activation, Dense
from tensorflow.keras.layers import Conv2D

os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'

path = '/Users/animalman/Documents/test/cnn/'

trainPath = os.listdir(path+'train')
testPath = os.listdir(path+'test')

categories = ["5"]
length = len(categories)

width = 28
height = 28
label = [1 for i in range(length)]
X = []
Y = []
for idx, categorie in enumerate(categories):
    label = [0 for i in range(length)]
    label[idx] = 1
    
    fileDir = path + 'train' + '/' + categorie + '/'
    for t, dir, f in os.walk(fileDir):
        for filename in f:
            print(fileDir + filename)
            img = cv2.imread(fileDir + filename)
            img = cv2.resize(img, None, fx=width/img.shape[0],fy=height/img.shape[1])
            X.append(img)
            Y.append(label)
X = np.array(X)
Y = np.array(Y)
X_train, X_test,Y_train, Y_test = train_test_split(X,Y)
xy = (X_train, X_test, Y_train, Y_test)


X_train = X_train.astype("float") / 256
X_test  = X_test.astype("float")  / 256

model = Sequential()
model.add(Conv2D(16, (3, 3), input_shape=X_train.shape[1:], padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))

model.add(Conv2D(64, (3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten()) 
model.add(Dense(512))  
model.add(Activation('relu'))
model.add(Dropout(0.5))

model.add(Dense(length))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
    optimizer='rmsprop',
    metrics=['accuracy'])


hdf5_file = "./7obj-model.h5"
if os.path.exists(hdf5_file):
    model.load_weights(hdf5_file)
else:
    model.fit(X_train, Y_train, batch_size=32, epochs=1)
    model.save_weights(hdf5_file)

And then I brought in the model file that was saved.

loaded_model = tf.keras.models.load_model(hdf5_file)

However, this is where the error occurs. What's the reason?

Traceback (most recent call last): File "/Users/animalman/Documents/test/train.py", line 112, in loaded_model = tf.keras.models.load_model(hdf5_file) File "/Users/animalman/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/saving/save.py", line 206, in load_model return hdf5_format.load_model_from_hdf5(filepath, custom_objects, File "/Users/animalman/opt/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 181, in load_model_from_hdf5 raise ValueError('No model found in config file.') ValueError: No model found in config file.

1

1 Answers

0
votes

As mentioned in this post, your h5 file only contains weights. You need to save your model architecture in a json file and then use model_from_json, to load model configuration, hence, you can load weights with load_weights.

Another option may be to simply save your model (architecture + weights together) by replacing your last line by

model.save("model.h5")

and then to load, you can make use of

model = load_model('model.h5')