我无法使用Keras加载保存的模型

时间:2020-03-27 15:05:57

标签: python tensorflow tf.keras

我试图保存一个keras模型并尝试加载它,但出现以下错误:

>     939                                  str(weights[0].size) + '. ')
>     940             weights[0] = np.reshape(weights[0], layer_weights_shape)
> --> 941         elif layer_weights_shape != weights[0].shape:
>     942             weights[0] = np.transpose(weights[0], (3, 2, 0, 1))
>     943             if layer.__class__.__name__ == 'ConvLSTM2D':

IndexError:列表索引超出范围

我的代码如下:

from keras.layers import Conv2D, BatchNormalization, \
    MaxPool2D, GlobalMaxPool2D
def build_mobilenet(shape=(112, 112, 3), nbout=2):
    model = keras.applications.mobilenet.MobileNet(
        include_top=False,
        input_shape=shape,
        weights='imagenet')
    # Keep 9 layers to train
    trainable = 9
    for layer in model.layers[:-trainable]:
        layer.trainable = False
    for layer in model.layers[-trainable:]:
        layer.trainable = True
    output = GlobalMaxPool2D()
    model.summary()
    return keras.Sequential([model, output])
build_mobilenet()

from keras.layers import TimeDistributed, GRU, Dense, Dropout
def action_model(shape=(5, 224, 224, 3), nbout=2):
    # Create our convnet with (112, 112, 3) input shape
    convnet = build_mobilenet(shape[1:])    
    # then create our final model
    model = keras.Sequential()
    # add the convnet with (5, 112, 112, 3) shape
    model.add(TimeDistributed(convnet, input_shape=shape))
    # here, you can also use GRU or LSTM
    model.add(GRU(64))
    # and finally, we make a decision network
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(.5))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(nbout, activation='softmax'))
    return model

我正在保存模型并将其加载到以下代码中:

model.save_weights("model_num.h5")
model = load_weights('model_num.h5') # this line shows the above error

0 个答案:

没有答案