如何部署CNN文件

时间:2019-05-14 06:41:07

标签: tensorflow keras

我已经使用此代码训练了一个模型...

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

我的文件已经准备好了,但是我该如何部署它?

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

我尝试使用托管解决方案panini.ai,但它不接受h5文件。我试图将其转换为csv,但这没有用。我也尝试使用烧瓶

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

尝试运行docker容器时出现此错误...

# 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.

换句话说,如何使用cnn.h5文件?


我正在尝试使用此代码...

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')

出现错误:

ValueError: You are trying to load a weight file containing 4 layers into a model with 2 layers.

3 个答案:

答案 0 :(得分:6)

关于第一个错误,我的问题是flask应用尝试加载完整的模型(即使用配置):

 model = load_model(MODEL_PATH)

在训练之后,您仅节省重量:

cnn.save_weights('cnn.h5')

尝试改用cnn.save('cnn.h5')

在第二种情况下,您的模型定义与训练的模型不匹配。实际上,它是完全不同的模型,完全没有卷积层。相应的模型定义为:

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

答案 1 :(得分:3)

您可以通过以下方式加载模型:

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

可以使用以下代码加载训练/测试数据:

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

答案 2 :(得分:0)

您训练有素的模型与您尝试加载的模型不同。 替换

cnn = Sequential()

使用

cnn = build_model()