How to load a model from an HDF5 file in Keras?

后端 未结 5 949
陌清茗
陌清茗 2020-12-07 08:03

How to load a model from an HDF5 file in Keras?

What I tried:

model = Sequential()

model.add(Dense(64, input_dim=14, init=\'uniform\'))
model.add(Le         


        
5条回答
  •  感动是毒
    2020-12-07 08:12

    See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

    # create model
    model = Sequential()
    model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
    model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
    model.add(Dense(output_dim, activation='softmax')) #Output Layer
    
    # Compile & Fit model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    
    
    # serialize model to JSON
    model_json = model.to_json()
    with open("Data/model.json", "w") as json_file:
        json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))
    
    # serialize weights to HDF5
    model.save_weights("Data/model.h5")
    print("Saved model to disk")
    
    # load json and create model
    json_file = open('Data/model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    
    # load weights into new model
    loaded_model.load_weights("Data/model.h5")
    print("Loaded model from disk")
    
    # evaluate loaded model on test data 
    # Define X_test & Y_test data first
    loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    score = loaded_model.evaluate(X_test, Y_test, verbose=0)
    print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
    

提交回复
热议问题