[Python] Do I need to call model.fit() function every time after loading the model using Keras

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am using Keras to create model :

    def my_model():
    model = Sequential()
    model.add(Conv2D(60, (5,5), input_shape=(32,32,1), activation='relu'))
    model.add(Conv2D(60, (5,5), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(30, (3,3), activation='relu'))
    model.add(Conv2D(30, (3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    #model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(500, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))
    ## Compile the model
    model.compile(Adam(learning_rate = 0.001), loss = 'categorical_crossentropy', metrics=['accuracy'])
    return model


    Now save the model and train it :

    model = my_model()
    print(model.summary())
    model.save('my_model.h5')
    history = model.fit(X_train, y_train, epochs = 10, validation_data=(X_val, y_val), batch_size = 400, verbose = 1, shuffle = 1)

    #### Now predict some image
    pred = model.predict(img)
    prediction = np.argmax(pred,axis=1)
    print("predicted sign: "+ str(prediction))


    'model.fit()' function is the most CPU intensive job. In a less-powerful platform it takes lot of time to train. Is it possible to save the trained model and just use it for the purpose of prediction ?

    I know there is way to load the saved model :

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


    However still I have to run 'model.fit()' which is CPU intensive. Is there any way to avoid model.fit() and load the model and use for prediction ?

    Continue reading...

Compartilhe esta Página