#UNQ_C1: Type error on grad_cam function (cam)

Lab ID: kuoautcopnzt

UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)

def grad_cam(input_model, image, category_index, layer_name):

The function works correctly. The type of cam is also correct (see output below):

type(cam): <class ‘numpy.ndarray’>
Error from reference should be less than 0.05
Your error from reference: 0.030968351

But the grader reports a type error:

Code Cell UNQ_C1: Unexpected error (InvalidArgumentError()) occurred during function check. We expected function grad_cam to return type <class ‘numpy.ndarray’>. Please check that this function is defined properly.
Code Cell UNQ_C2: Function ‘compute_gradcam’ is correct.
Code Cell UNQ_C3: Function ‘permute_feature’ is correct.
Code Cell UNQ_C4: Function ‘permutation_importance’ is correct.
If you see many functions being marked as incorrect, try to trace back your steps & identify if there is an incorrect function that is being used in other steps.
This dependency may be the cause of the errors.

HI @getjaidev,

Try to refresh your lab workspace.

Steps are given below.

  1. Rename and save your existing file.
  2. In your home Lab workspace, add “?forceRefresh=true” to the end of your Lab URL.
  3. Press Enter to reload the screen.
  4. You should see both your old and new files in the Learner Workspace after refresh.
  5. Your Lab item should now launch to the fresh lab file.

Please let me know if you still face the issue.

Thanks,
Girijesh

Hi @Girijesh

I am getting the same error. I have two notebooks now. One the original and one a copy after the refresh.

I loaded both and still have the error.

Code Cell UNQ_C1: Unexpected error (InvalidArgumentError()) occurred during function check. We expected function grad_cam to return type <class ‘numpy.ndarray’>. Please check that this function is defined properly.
Code Cell UNQ_C2: Function ‘compute_gradcam’ is correct.
Code Cell UNQ_C3: Function ‘permute_feature’ is correct.
Code Cell UNQ_C4: Function ‘permutation_importance’ is correct.
If you see many functions being marked as incorrect, try to trace back your steps & identify if there is an incorrect function that is being used in other steps.
This dependency may be the cause of the errors.

Regards.

@Juan_Olano @Mubsi @Girijesh

Just fyi. These type errors are some of the ore common ones I have faced and they are tough to debug with grader. Aside (as in, that is not the problem here), I think the specific return types expected should be made part of the instruction/comments. Will just help guide the student.

Hi @getjaidev,

Firstly, I do agree with you here that the output of the grader is not at all helpful in this case. I should see what I can do about it.

With that being said, your code was somehow passing the test case, but was incorrect. Your code was unnecessarily complex and long, and was referencing variables in not the sequential order as proposed in the assignment. In some instances, you were using the global variable model instead of using the function parameter of the model provided.

I have fixed your code in your notebook, you can take a look at it for more detail. It now passes all the tests. Please use the file C3_W3_Assignment.ipynb.

As a reference, this is the exercise code and you can see how the order was different in your notebook.

# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def grad_cam(input_model, image, category_index, layer_name):
    """
    GradCAM method for visualizing input saliency.
    
    Args:
        input_model (Keras.model): model to compute cam for
        image (tensor): input to model, shape (1, H, W, 3), where H (int) is height W (int) is width
        category_index (int): class to compute cam with respect to
        layer_name (str): relevant layer in model
    Return:
        cam ()
    """
    cam = None
    
    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###

    # 1. Get placeholders for class output and last layer
    # Get the model's output
    output_with_batch_dim = None
    
    # Remove the batch dimension
    output_all_categories = None
    
    # Retrieve only the disease category at the given category index
    y_c = None
    
    # Get the input model's layer specified by layer_name, and retrive the layer's output tensor
    spatial_map_layer = None

    # 2. Get gradients of last layer with respect to output

    # get the gradients of y_c with respect to the spatial map layer (it's a list of length 1)
    grads_l = None
    
    # Get the gradient at index 0 of the list
    grads = None
        
    # 3. Get hook for the selected layer and its gradient, based on given model's input
    # Hint: Use the variables produced by the previous two lines of code
    spatial_map_and_gradient_function = None
    
    # Put in the image to calculate the values of the spatial_maps (selected layer) and values of the gradients
    spatial_map_all_dims, grads_val_all_dims = None

    # Reshape activations and gradient to remove the batch dimension
    # Shape goes from (B, H, W, C) to (H, W, C)
    # B: Batch. H: Height. W: Width. C: Channel    
    # Reshape spatial map output to remove the batch dimension
    spatial_map_val = None
    
    # Reshape gradients to remove the batch dimension
    grads_val = None
    
    # 4. Compute weights using global average pooling on gradient 
    # grads_val has shape (Height, Width, Channels) (H,W,C)
    # Take the mean across the height and also width, for each channel
    # Make sure weights have shape (C)
    weights = None
    
    # 5. Compute dot product of spatial map values with the weights
    cam = None

    ### END CODE HERE ###
    
    # We'll take care of the postprocessing.
    H, W = image.shape[1], image.shape[2]
    cam = np.maximum(cam, 0) # ReLU so we only get positive importance
    cam = cv2.resize(cam, (W, H), cv2.INTER_NEAREST)
    cam = cam / cam.max()

    return cam

Congratulations on completing the specialisation!

All the best,
Mubsi

@mubsi Thanks for your help.

I am happy to complete the specialization! This is a very good course I think.

As for the comments on the code, I just have a lot of debug print statements. The code is actually not at all long :slight_smile:

After looking at the corrections, I think the only problem (just one mistake) was with the “model” instead of “input_model” by mistake. All the other lines are exactly the same although the variable names I used might be different. Will send you an direct message with my code anyways to expand on that!

Thanks and again. Your help throughout the journey, as of the other mentors as well, has been quick and very useful. Appreciate it.

Best Regards.