2

I am trying to visualize gradient (gradcam) for a keras model in R.

Here's the code with MNIST dataset:

library(keras)
fashion_mnist <- dataset_fashion_mnist()

c(train_images, train_labels) %<-% fashion_mnist$train
c(test_images, test_labels) %<-% fashion_mnist$test
class_names = c('T-shirt/top',
                'Trouser',
                'Pullover',
                'Dress',
                'Coat',
                'Sandal',
                'Shirt',
                'Sneaker',
                'Bag',
                'Ankle boot')

train_images <- train_images / 255
test_images <- test_images / 255

model <- keras_model_sequential()
model %>%
  layer_flatten(input_shape = c(28, 28)) %>%
  layer_dense(units = 128, activation = 'relu') %>%
  layer_dense(units = 10, activation = 'softmax')

model %>% compile(
  optimizer = 'adam',
  loss = 'sparse_categorical_crossentropy',
  metrics = c('accuracy')
)

model %>% fit(train_images, train_labels, epochs = 5, verbose = 2)


img <- test_images[1, , , drop = FALSE]

predictions <- model %>% predict(img)


img_output <- model$output[, 1]

last_layer <- model %>% get_layer("dense_4")

grads <- k_gradients(img_output, last_layer$output)[[1]]

I am following these instructions: https://rstudio-conf-2020.github.io/dl-keras-tf/notebooks/visualizing-what-cnns-learn.nb.html

And I am getting this error:

RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead.

I found this solution from here:

tf$compat$v1$disable_eager_execution()

However, adding this to the top of the code produce the other error:

  AttributeError: 'Tensor' object has no attribute 'gradient'

while running this:

pooled_grads <- k_mean(grads$gradient, axis = c(1, 2, 3))

Can you help me? I need something like this: grad vis

0

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.