How to predict after creating keras model (done after 'complie', 'fit', 'history'..)?


I am a beginner of keras and tensorflow. I bought the book, Deep learning in R' and tried to follow the example code.
But here, I am wondering after I made the model using 'keras_model_sequential'. I did complied model and all ex code said about checking the history with 'fit' or 'fit_generator' lilke

history <- model %>% fit_generator(
steps_per_epoch = 500,
epoch = 20,
validation_data = val_gen,
validation_steps = val_steps

then? then what? where is the prediction? how can I predict other data or test data?
maybe it is silly question, but please help me understand.



Welcome to the community!

I'm learning keras myself, but with python. There, if you have a fitted model, say model, you can predict using model.predict(testX).

In the R version (which I haven't used myself), there are functions predict and predict_classes.

You can look at the examples provided here and here.



The keras models behave differently than most other R objects. They are modified in place, meaning after passing the training results to the history object (which will contain training metrics and so on) the model object itself will be different (trained).

You can (and should; a model takes a while to train) save it by piping it to the save_model_hdf5() function:

model %>% 

The hdf5 file is universal, meaning that it can be read and understood by the snake people. Which is kinda helpful, as there seems to be more Python than R Keras practitioners.

Making a prediction is easy - you take a trained model (either immediately after training, or more likely loaded by load_model_hdf5() function - and pipe to it a predict_... function; in this case predict_proba() = predicting probability of classes. Obviously the input_matrix object needs to have the same dimensions as your training dataset; the output will be a matrix of class probabilities.

pred <- model %>% 


Thank you for the advice, I will try and report the results!



Which, btw, is how objects “work” in most OOP languages. You apply a class method on the object, and the object itself is modified (which is why you see that special argument self in the definition of said methods).

1 Like

closed #6

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.