7

I have trained a model using this code...

https://github.com/shantanuo/pandas_examples/blob/master/tensorflow/simages_train_waiting.ipynb

My file is ready, but how do I deploy it?

https://s3.ap-south-1.amazonaws.com/studentimages162a/cnn.h5

I tried to use hosted solution panini.ai but it does not accept h5 files. I tried to convert it to csv but that did not work. I also tried to use flask

https://github.com/mtobeiyf/keras-flask-deploy-webapp

I got this error while trying to run the docker container...

# docker run -v /tmp/:/tmp/ -p 5000:5000 keras_flask_app
Using TensorFlow backend.
Traceback (most recent call last):
  File "app.py", line 26, in <module>
    model = load_model(MODEL_PATH)
  File "/usr/local/lib/python2.7/site-packages/keras/engine/saving.py", line 419, in load_model
    model = _deserialize_model(f, custom_objects, compile)
  File "/usr/local/lib/python2.7/site-packages/keras/engine/saving.py", line 221, in _deserialize_model
    model_config = f['model_config']
  File "/usr/local/lib/python2.7/site-packages/keras/utils/io_utils.py", line 302, in __getitem__
    raise ValueError('Cannot create group in read only mode.')
ValueError: Cannot create group in read only mode.

In other words how to use cnn.h5 file?


I am trying to use this code...

from keras.models import Sequential
from keras.layers import Dense, Activation

def build_model():
    model = Sequential()

    model.add(Dense(output_dim=64, input_dim=100))
    model.add(Activation("relu"))
    model.add(Dense(output_dim=10))
    model.add(Activation("softmax"))
    model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
    return model

model2 = build_model()
model2.load_weights('cnn.h5')

And got the error:

ValueError: You are trying to load a weight file containing 4 layers into a model with 2 layers.
3
  • Can you show the code for deployment how you are doing? Commented May 14, 2019 at 6:47
  • By deployment do you refer to being able to save and reload from disk the H5 model? Commented May 22, 2019 at 22:39
  • @Siavas Yes! That's correct. Commented May 23, 2019 at 6:18

3 Answers 3

6
+25

Concerning the first error, I the problem is that the flask app tries to load the complete model (i.e. with configuration):

 model = load_model(MODEL_PATH)

whereas after the training you save only weights:

cnn.save_weights('cnn.h5')

Try to use cnn.save('cnn.h5') instead.

In the second case, your model definition does not match the trained model. Indeed, it is a completely different model with no Convolution layers at all. The corresponding model definition would be:

def build_model():
    model = Sequential()

    model.add(Conv2D(filters=32, 
           kernel_size=(2,2), 
           strides=(1,1),
           padding='same',
           input_shape=(IMG_SIZE,IMG_SIZE,NB_CHANNELS),
           data_format='channels_last'))


    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2),
                           strides=2))

    model.add(Dropout(0.4))

    model.add(Conv2D(filters=64,
                     kernel_size=(2,2),
                     strides=(1,1),
                     padding='valid'))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2),
                           strides=2))

    model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
    return model
Sign up to request clarification or add additional context in comments.

2 Comments

I tried to train using your code. Does this look OK? github.com/shantanuo/testcnn/blob/master/…
As Rajneesh Aggarwal suggested, it would be better to call load_model to read the configuration from file. If you prefer to define architecture and then load only weights, I can offer you 1) use build_model to create cnn as well, because currently you have code duplication and 2) give names to the layers and call model.load_weights(..., by_name=True)
3

You can load the model in following way:

from tensorflow.keras.models import load_model
model = load_model('cnn.h5')

The training/test data can be loaded with the following code:

import h5py
import numpy as np
hf = h5py.File('cnn.h5', 'r')

Comments

0

Your trained model and the model you are trying to load differ. Replace

cnn = Sequential()

with

cnn = build_model()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.