0

I've created a CNN in RStudio using keras to predict MNIST digits. I am now trying to predict with this model using the following code

cnn_pred <- cnn_model %>%
    predict_classes(x_test)

but predict_classes() has been deprecated and I need something to replace it. I've tried using just predict() but it results in continuous predictions when I need it to predict what the digit is (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9).

What function can be used with the CNN model to give a categorical prediction?

3 Answers 3

1

This is a convoluted way, but I managed to get it to work. I first had to get the array from the tf object, which turned out to be a python array, so then had to convert it to R object. And then I could compare/do calculations on that against another r object.

This is the prediction on the test data, output (prednn.tf) is a tensor:

prednn.tf <- modelnn %>% predict(x_test) %>% k_argmax() 

Now convert from tensor to an array using np_array:

prednn.array <- np_array(prednn.tf)

Now to a r-object:

prednn.array <- reticulate::py_to_r(prednn.array) 

Now compare the prediction against actual and calculate the accuracy:

accuracy(prednn.array, g_test) 

Note - following is the accuracy function:

accuracy <- function(pred, truth)
  mean(drop(pred) == drop(truth))

All this because predict_classes() is deprecated. There might be an easier way, but this worked for me.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use

cnn_pred <- cnn_model %>%
    predict(x_test) %>% k_argmax()


1 Comment

how do I view the numbers that the model predicted?
0

In my example, seems an even easier method was to do this:

change accuracy function from:

accuracy <- function(pred, truth)
  mean(drop(pred) == drop(truth))

to:

accuracy <- function(pred, truth)
  mean(drop(as.numeric(pred)) == drop(truth))

and then the following works:

modelnn %>% predict(x_test) %>% k_argmax() %>% accuracy(g_test)

so it seems, as.numeric() will take the tensor and extract the values. Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.